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/CodeGen/LiveVariables.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/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/STLExtras.h"
38 STATISTIC(numJoins , "Number of interval joins performed");
39 STATISTIC(numCommutes , "Number of instruction commuting performed");
40 STATISTIC(numExtends , "Number of copies extended");
41 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
42 STATISTIC(numAborts , "Number of times interval joining aborted");
44 char SimpleRegisterCoalescing::ID = 0;
47 EnableJoining("join-liveintervals",
48 cl::desc("Coalesce copies (default=true)"),
52 NewHeuristic("new-coalescer-heuristic",
53 cl::desc("Use new coalescer heuristic"),
56 RegisterPass<SimpleRegisterCoalescing>
57 X("simple-register-coalescing", "Simple Register Coalescing");
59 // Declare that we implement the RegisterCoalescer interface
60 RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
63 const PassInfo *llvm::SimpleRegisterCoalescingID = X.getPassInfo();
65 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
66 AU.addPreserved<LiveIntervals>();
67 AU.addPreserved<MachineLoopInfo>();
68 AU.addPreservedID(MachineDominatorsID);
69 AU.addPreservedID(PHIEliminationID);
70 AU.addPreservedID(TwoAddressInstructionPassID);
71 AU.addRequired<LiveVariables>();
72 AU.addRequired<LiveIntervals>();
73 AU.addRequired<MachineLoopInfo>();
74 MachineFunctionPass::getAnalysisUsage(AU);
77 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
78 /// being the source and IntB being the dest, thus this defines a value number
79 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
80 /// see if we can merge these two pieces of B into a single value number,
81 /// eliminating a copy. For example:
85 /// B1 = A3 <- this copy
87 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
88 /// value number to be replaced with B0 (which simplifies the B liveinterval).
90 /// This returns true if an interval was modified.
92 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
94 MachineInstr *CopyMI) {
95 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
97 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
99 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
100 if (BLR == IntB.end()) // Should never happen!
102 VNInfo *BValNo = BLR->valno;
104 // Get the location that B is defined at. Two options: either this value has
105 // an unknown definition point or it is defined at CopyIdx. If unknown, we
107 if (!BValNo->copy) return false;
108 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
110 // AValNo is the value number in A that defines the copy, A3 in the example.
111 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
112 if (ALR == IntA.end()) // Should never happen!
114 VNInfo *AValNo = ALR->valno;
116 // If AValNo is defined as a copy from IntB, we can potentially process this.
117 // Get the instruction that defines this value number.
118 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
119 if (!SrcReg) return false; // Not defined by a copy.
121 // If the value number is not defined by a copy instruction, ignore it.
123 // If the source register comes from an interval other than IntB, we can't
125 if (SrcReg != IntB.reg) return false;
127 // Get the LiveRange in IntB that this value number starts with.
128 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
129 if (ValLR == IntB.end()) // Should never happen!
132 // Make sure that the end of the live range is inside the same block as
134 MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
136 ValLREndInst->getParent() != CopyMI->getParent()) return false;
138 // Okay, we now know that ValLR ends in the same block that the CopyMI
139 // live-range starts. If there are no intervening live ranges between them in
140 // IntB, we can merge them.
141 if (ValLR+1 != BLR) return false;
143 // If a live interval is a physical register, conservatively check if any
144 // of its sub-registers is overlapping the live interval of the virtual
145 // register. If so, do not coalesce.
146 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
147 *tri_->getSubRegisters(IntB.reg)) {
148 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
149 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
150 DOUT << "Interfere with sub-register ";
151 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
156 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
158 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
159 // We are about to delete CopyMI, so need to remove it as the 'instruction
160 // that defines this value #'. Update the the valnum with the new defining
162 BValNo->def = FillerStart;
165 // Okay, we can merge them. We need to insert a new liverange:
166 // [ValLR.end, BLR.begin) of either value number, then we merge the
167 // two value numbers.
168 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
170 // If the IntB live range is assigned to a physical register, and if that
171 // physreg has aliases,
172 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
173 // Update the liveintervals of sub-registers.
174 for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) {
175 LiveInterval &AliasLI = li_->getInterval(*AS);
176 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
177 AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
181 // Okay, merge "B1" into the same value number as "B0".
182 if (BValNo != ValLR->valno)
183 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
184 DOUT << " result = "; IntB.print(DOUT, tri_);
187 // If the source instruction was killing the source register before the
188 // merge, unset the isKill marker given the live range has been extended.
189 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
191 ValLREndInst->getOperand(UIdx).setIsKill(false);
197 /// HasOtherReachingDefs - Return true if there are definitions of IntB
198 /// other than BValNo val# that can reach uses of AValno val# of IntA.
199 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
203 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
205 if (AI->valno != AValNo) continue;
206 LiveInterval::Ranges::iterator BI =
207 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
208 if (BI != IntB.ranges.begin())
210 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
211 if (BI->valno == BValNo)
213 if (BI->start <= AI->start && BI->end > AI->start)
215 if (BI->start > AI->start && BI->start < AI->end)
222 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
223 /// being the source and IntB being the dest, thus this defines a value number
224 /// in IntB. If the source value number (in IntA) is defined by a commutable
225 /// instruction and its other operand is coalesced to the copy dest register,
226 /// see if we can transform the copy into a noop by commuting the definition. For
229 /// A3 = op A2 B0<kill>
231 /// B1 = A3 <- this copy
233 /// = op A3 <- more uses
237 /// B2 = op B0 A2<kill>
239 /// B1 = B2 <- now an identify copy
241 /// = op B2 <- more uses
243 /// This returns true if an interval was modified.
245 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
247 MachineInstr *CopyMI) {
248 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
250 // FIXME: For now, only eliminate the copy by commuting its def when the
251 // source register is a virtual register. We want to guard against cases
252 // where the copy is a back edge copy and commuting the def lengthen the
253 // live interval of the source register to the entire loop.
254 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
257 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
258 // the example above.
259 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
260 if (BLR == IntB.end()) // Should never happen!
262 VNInfo *BValNo = BLR->valno;
264 // Get the location that B is defined at. Two options: either this value has
265 // an unknown definition point or it is defined at CopyIdx. If unknown, we
267 if (!BValNo->copy) return false;
268 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
270 // AValNo is the value number in A that defines the copy, A3 in the example.
271 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
272 if (ALR == IntA.end()) // Should never happen!
274 VNInfo *AValNo = ALR->valno;
275 // If other defs can reach uses of this def, then it's not safe to perform
277 if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
279 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
280 const TargetInstrDesc &TID = DefMI->getDesc();
282 if (!TID.isCommutable() ||
283 !tii_->CommuteChangesDestination(DefMI, NewDstIdx))
286 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
287 unsigned NewReg = NewDstMO.getReg();
288 if (NewReg != IntB.reg || !NewDstMO.isKill())
291 // Make sure there are no other definitions of IntB that would reach the
292 // uses which the new definition can reach.
293 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
296 // If some of the uses of IntA.reg is already coalesced away, return false.
297 // It's not possible to determine whether it's safe to perform the coalescing.
298 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
299 UE = mri_->use_end(); UI != UE; ++UI) {
300 MachineInstr *UseMI = &*UI;
301 unsigned UseIdx = li_->getInstructionIndex(UseMI);
302 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
303 if (ULR == IntA.end())
305 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
309 // At this point we have decided that it is legal to do this
310 // transformation. Start by commuting the instruction.
311 MachineBasicBlock *MBB = DefMI->getParent();
312 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
315 if (NewMI != DefMI) {
316 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
317 MBB->insert(DefMI, NewMI);
320 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
321 NewMI->getOperand(OpIdx).setIsKill();
323 bool BHasPHIKill = BValNo->hasPHIKill;
324 SmallVector<VNInfo*, 4> BDeadValNos;
325 SmallVector<unsigned, 4> BKills;
326 std::map<unsigned, unsigned> BExtend;
328 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
337 // then do not add kills of A to the newly created B interval.
338 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
340 BExtend[ALR->end] = BLR->end;
342 // Update uses of IntA of the specific Val# with IntB.
343 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
344 UE = mri_->use_end(); UI != UE;) {
345 MachineOperand &UseMO = UI.getOperand();
346 MachineInstr *UseMI = &*UI;
348 if (JoinedCopies.count(UseMI))
350 unsigned UseIdx = li_->getInstructionIndex(UseMI);
351 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
352 if (ULR == IntA.end() || ULR->valno != AValNo)
354 UseMO.setReg(NewReg);
357 if (UseMO.isKill()) {
359 UseMO.setIsKill(false);
361 BKills.push_back(li_->getUseIndex(UseIdx)+1);
363 unsigned SrcReg, DstReg;
364 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg))
366 if (DstReg == IntB.reg) {
367 // This copy will become a noop. If it's defining a new val#,
368 // remove that val# as well. However this live range is being
369 // extended to the end of the existing live range defined by the copy.
370 unsigned DefIdx = li_->getDefIndex(UseIdx);
371 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
372 BHasPHIKill |= DLR->valno->hasPHIKill;
373 assert(DLR->valno->def == DefIdx);
374 BDeadValNos.push_back(DLR->valno);
375 BExtend[DLR->start] = DLR->end;
376 JoinedCopies.insert(UseMI);
377 // If this is a kill but it's going to be removed, the last use
378 // of the same val# is the new kill.
384 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
385 // simply extend BLR if CopyMI doesn't end the range.
386 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
388 IntB.removeValNo(BValNo);
389 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
390 IntB.removeValNo(BDeadValNos[i]);
391 VNInfo *ValNo = IntB.getNextValue(AValNo->def, 0, li_->getVNInfoAllocator());
392 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
394 if (AI->valno != AValNo) continue;
395 unsigned End = AI->end;
396 std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
397 if (EI != BExtend.end())
399 IntB.addRange(LiveRange(AI->start, End, ValNo));
401 IntB.addKills(ValNo, BKills);
402 ValNo->hasPHIKill = BHasPHIKill;
404 DOUT << " result = "; IntB.print(DOUT, tri_);
407 DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
408 IntA.removeValNo(AValNo);
409 DOUT << " result = "; IntA.print(DOUT, tri_);
416 /// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
418 bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
419 unsigned DstReg) const {
420 MachineBasicBlock *MBB = CopyMI->getParent();
421 const MachineLoop *L = loopInfo->getLoopFor(MBB);
424 if (MBB != L->getLoopLatch())
427 LiveInterval &LI = li_->getInterval(DstReg);
428 unsigned DefIdx = li_->getInstructionIndex(CopyMI);
429 LiveInterval::const_iterator DstLR =
430 LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
431 if (DstLR == LI.end())
433 unsigned KillIdx = li_->getInstructionIndex(&MBB->back()) + InstrSlots::NUM;
434 if (DstLR->valno->kills.size() == 1 &&
435 DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
440 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
441 /// update the subregister number if it is not zero. If DstReg is a
442 /// physical register and the existing subregister number of the def / use
443 /// being updated is not zero, make sure to set it to the correct physical
446 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
448 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
449 if (DstIsPhys && SubIdx) {
450 // Figure out the real physical register we are updating with.
451 DstReg = tri_->getSubReg(DstReg, SubIdx);
455 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
456 E = mri_->reg_end(); I != E; ) {
457 MachineOperand &O = I.getOperand();
458 MachineInstr *UseMI = &*I;
460 unsigned OldSubIdx = O.getSubReg();
462 unsigned UseDstReg = DstReg;
464 UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
468 // Sub-register indexes goes from small to large. e.g.
469 // RAX: 0 -> AL, 1 -> AH, 2 -> AX, 3 -> EAX
470 // EAX: 0 -> AL, 1 -> AH, 2 -> AX
471 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
472 // sub-register 2 is also AX.
473 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
474 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
477 // Remove would-be duplicated kill marker.
478 if (O.isKill() && UseMI->killsRegister(DstReg))
485 /// RemoveDeadImpDef - Remove implicit_def instructions which are "re-defining"
486 /// registers due to insert_subreg coalescing. e.g.
488 /// r1025 = implicit_def
489 /// r1025 = insert_subreg r1025, r1024
493 /// r1025 = implicit_def
494 /// r1025 = insert_subreg r1025, r1025
497 SimpleRegisterCoalescing::RemoveDeadImpDef(unsigned Reg, LiveInterval &LI) {
498 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
499 E = mri_->reg_end(); I != E; ) {
500 MachineOperand &O = I.getOperand();
501 MachineInstr *DefMI = &*I;
505 if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
507 if (!LI.liveBeforeAndAt(li_->getInstructionIndex(DefMI)))
509 li_->RemoveMachineInstrFromMaps(DefMI);
510 DefMI->eraseFromParent();
514 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
515 /// due to live range lengthening as the result of coalescing.
516 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
518 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
519 UE = mri_->use_end(); UI != UE; ++UI) {
520 MachineOperand &UseMO = UI.getOperand();
521 if (UseMO.isKill()) {
522 MachineInstr *UseMI = UseMO.getParent();
524 if (!tii_->isMoveInstr(*UseMI, SReg, DReg))
526 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
527 if (JoinedCopies.count(UseMI))
529 const LiveRange *UI = LI.getLiveRangeContaining(UseIdx);
530 if (!LI.isKill(UI->valno, UseIdx+1))
531 UseMO.setIsKill(false);
536 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
537 /// from a physical register live interval as well as from the live intervals
538 /// of its sub-registers.
539 static void removeRange(LiveInterval &li, unsigned Start, unsigned End,
540 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
541 li.removeRange(Start, End, true);
542 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
543 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
544 if (!li_->hasInterval(*SR))
546 LiveInterval &sli = li_->getInterval(*SR);
547 unsigned RemoveEnd = Start;
548 while (RemoveEnd != End) {
549 LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
552 RemoveEnd = (LR->end < End) ? LR->end : End;
553 sli.removeRange(Start, RemoveEnd, true);
560 /// removeIntervalIfEmpty - Check if the live interval of a physical register
561 /// is empty, if so remove it and also remove the empty intervals of its
562 /// sub-registers. Return true if live interval is removed.
563 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
564 const TargetRegisterInfo *tri_) {
566 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
567 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
568 if (!li_->hasInterval(*SR))
570 LiveInterval &sli = li_->getInterval(*SR);
572 li_->removeInterval(*SR);
574 li_->removeInterval(li.reg);
580 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
581 /// Return true if live interval is removed.
582 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
583 MachineInstr *CopyMI) {
584 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
585 LiveInterval::iterator MLR =
586 li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
588 return false; // Already removed by ShortenDeadCopySrcLiveRange.
589 unsigned RemoveStart = MLR->start;
590 unsigned RemoveEnd = MLR->end;
591 // Remove the liverange that's defined by this.
592 if (RemoveEnd == li_->getDefIndex(CopyIdx)+1) {
593 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
594 return removeIntervalIfEmpty(li, li_, tri_);
599 /// PropagateDeadness - Propagate the dead marker to the instruction which
600 /// defines the val#.
601 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
602 unsigned &LRStart, LiveIntervals *li_,
603 const TargetRegisterInfo* tri_) {
604 MachineInstr *DefMI =
605 li_->getInstructionFromIndex(li_->getDefIndex(LRStart));
606 if (DefMI && DefMI != CopyMI) {
607 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false, tri_);
609 DefMI->getOperand(DeadIdx).setIsDead();
610 // A dead def should have a single cycle interval.
616 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
617 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
618 /// ends the live range there. If there isn't another use, then this live range
619 /// is dead. Return true if live interval is removed.
621 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
622 MachineInstr *CopyMI) {
623 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
625 // FIXME: special case: function live in. It can be a general case if the
626 // first instruction index starts at > 0 value.
627 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
628 // Live-in to the function but dead. Remove it from entry live-in set.
629 mf_->begin()->removeLiveIn(li.reg);
630 const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
631 removeRange(li, LR->start, LR->end, li_, tri_);
632 return removeIntervalIfEmpty(li, li_, tri_);
635 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx-1);
637 // Livein but defined by a phi.
640 unsigned RemoveStart = LR->start;
641 unsigned RemoveEnd = li_->getDefIndex(CopyIdx)+1;
642 if (LR->end > RemoveEnd)
643 // More uses past this copy? Nothing to do.
647 MachineOperand *LastUse = lastRegisterUse(LR->start, CopyIdx-1, li.reg,
650 // There are uses before the copy, just shorten the live range to the end
652 LastUse->setIsKill();
653 MachineInstr *LastUseMI = LastUse->getParent();
654 removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
655 unsigned SrcReg, DstReg;
656 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg) &&
658 // Last use is itself an identity code.
659 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
660 LastUseMI->getOperand(DeadIdx).setIsDead();
666 MachineBasicBlock *CopyMBB = CopyMI->getParent();
667 unsigned MBBStart = li_->getMBBStartIdx(CopyMBB);
668 if (LR->start <= MBBStart && LR->end > MBBStart) {
669 if (LR->start == 0) {
670 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
671 // Live-in to the function but dead. Remove it from entry live-in set.
672 mf_->begin()->removeLiveIn(li.reg);
674 // FIXME: Shorten intervals in BBs that reaches this BB.
677 if (LR->valno->def == RemoveStart)
678 // If the def MI defines the val#, propagate the dead marker.
679 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
681 removeRange(li, RemoveStart, LR->end, li_, tri_);
682 return removeIntervalIfEmpty(li, li_, tri_);
685 /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
686 /// from an implicit def to another register can be coalesced away.
687 bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
689 LiveInterval &ImpLi) const{
690 if (!CopyMI->killsRegister(ImpLi.reg))
692 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
693 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx);
696 if (LR->valno->hasPHIKill)
698 if (LR->valno->def != CopyIdx)
700 // Make sure all of val# uses are copies.
701 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(li.reg),
702 UE = mri_->use_end(); UI != UE;) {
703 MachineInstr *UseMI = &*UI;
705 if (JoinedCopies.count(UseMI))
707 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
708 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
709 if (ULR == li.end() || ULR->valno != LR->valno)
711 // If the use is not a use, then it's not safe to coalesce the move.
712 unsigned SrcReg, DstReg;
713 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg)) {
714 if (UseMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG &&
715 UseMI->getOperand(1).getReg() == li.reg)
724 /// RemoveCopiesFromValNo - The specified value# is defined by an implicit
725 /// def and it is being removed. Turn all copies from this value# into
726 /// identity copies so they will be removed.
727 void SimpleRegisterCoalescing::RemoveCopiesFromValNo(LiveInterval &li,
729 MachineInstr *ImpDef = NULL;
730 MachineOperand *LastUse = NULL;
731 unsigned LastUseIdx = li_->getUseIndex(VNI->def);
732 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg),
733 RE = mri_->reg_end(); RI != RE;) {
734 MachineOperand *MO = &RI.getOperand();
735 MachineInstr *MI = &*RI;
738 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
739 assert(!ImpDef && "Multiple implicit_def defining same register?");
744 if (JoinedCopies.count(MI))
746 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(MI));
747 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
748 if (ULR == li.end() || ULR->valno != VNI)
750 // If the use is a copy, turn it into an identity copy.
751 unsigned SrcReg, DstReg;
752 if (tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == li.reg) {
753 // Each use MI may have multiple uses of this register. Change them all.
754 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
755 MachineOperand &MO = MI->getOperand(i);
756 if (MO.isReg() && MO.getReg() == li.reg)
759 JoinedCopies.insert(MI);
760 } else if (UseIdx > LastUseIdx) {
766 LastUse->setIsKill();
768 // Remove dead implicit_def.
769 li_->RemoveMachineInstrFromMaps(ImpDef);
770 ImpDef->eraseFromParent();
774 static unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
775 const TargetRegisterClass *RC,
776 const TargetRegisterInfo* TRI) {
777 for (const unsigned *SRs = TRI->getSuperRegisters(Reg);
778 unsigned SR = *SRs; ++SRs)
779 if (Reg == TRI->getSubReg(SR, SubIdx) && RC->contains(SR))
784 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
785 /// which are the src/dst of the copy instruction CopyMI. This returns true
786 /// if the copy was successfully coalesced away. If it is not currently
787 /// possible to coalesce this interval, but it may be possible if other
788 /// things get coalesced, then it returns true by reference in 'Again'.
789 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
790 MachineInstr *CopyMI = TheCopy.MI;
793 if (JoinedCopies.count(CopyMI))
794 return false; // Already done.
796 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
800 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
801 bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG;
804 DstReg = CopyMI->getOperand(0).getReg();
805 SrcReg = CopyMI->getOperand(1).getReg();
806 } else if (isInsSubReg) {
807 if (CopyMI->getOperand(2).getSubReg()) {
808 DOUT << "\tSource of insert_subreg is already coalesced "
809 << "to another register.\n";
810 return false; // Not coalescable.
812 DstReg = CopyMI->getOperand(0).getReg();
813 SrcReg = CopyMI->getOperand(2).getReg();
814 } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
815 assert(0 && "Unrecognized copy instruction!");
819 // If they are already joined we continue.
820 if (SrcReg == DstReg) {
821 DOUT << "\tCopy already coalesced.\n";
822 return false; // Not coalescable.
825 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
826 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
828 // If they are both physical registers, we cannot join them.
829 if (SrcIsPhys && DstIsPhys) {
830 DOUT << "\tCan not coalesce physregs.\n";
831 return false; // Not coalescable.
834 // We only join virtual registers with allocatable physical registers.
835 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
836 DOUT << "\tSrc reg is unallocatable physreg.\n";
837 return false; // Not coalescable.
839 if (DstIsPhys && !allocatableRegs_[DstReg]) {
840 DOUT << "\tDst reg is unallocatable physreg.\n";
841 return false; // Not coalescable.
844 unsigned RealDstReg = 0;
845 unsigned RealSrcReg = 0;
846 if (isExtSubReg || isInsSubReg) {
847 SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
848 if (SrcIsPhys && isExtSubReg) {
849 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
850 // coalesced with AX.
851 unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
853 // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
854 // coalesced to a larger register so the subreg indices cancel out.
855 if (DstSubIdx != SubIdx) {
856 DOUT << "\t Sub-register indices mismatch.\n";
857 return false; // Not coalescable.
860 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
862 } else if (DstIsPhys && isInsSubReg) {
863 // EAX = INSERT_SUBREG EAX, r1024, 0
864 unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
866 // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
867 // coalesced to a larger register so the subreg indices cancel out.
868 if (SrcSubIdx != SubIdx) {
869 DOUT << "\t Sub-register indices mismatch.\n";
870 return false; // Not coalescable.
873 DstReg = tri_->getSubReg(DstReg, SubIdx);
875 } else if ((DstIsPhys && isExtSubReg) || (SrcIsPhys && isInsSubReg)) {
876 // If this is a extract_subreg where dst is a physical register, e.g.
877 // cl = EXTRACT_SUBREG reg1024, 1
878 // then create and update the actual physical register allocated to RHS.
880 // reg1024 = INSERT_SUBREG r1024, cl, 1
881 if (CopyMI->getOperand(1).getSubReg()) {
882 DOUT << "\tSrc of extract_ / insert_subreg already coalesced with reg"
883 << " of a super-class.\n";
884 return false; // Not coalescable.
886 const TargetRegisterClass *RC =
887 mri_->getRegClass(isExtSubReg ? SrcReg : DstReg);
889 RealDstReg = getMatchingSuperReg(DstReg, SubIdx, RC, tri_);
890 assert(RealDstReg && "Invalid extra_subreg instruction!");
892 RealSrcReg = getMatchingSuperReg(SrcReg, SubIdx, RC, tri_);
893 assert(RealSrcReg && "Invalid extra_subreg instruction!");
896 // For this type of EXTRACT_SUBREG, conservatively
897 // check if the live interval of the source register interfere with the
898 // actual super physical register we are trying to coalesce with.
899 unsigned PhysReg = isExtSubReg ? RealDstReg : RealSrcReg;
900 LiveInterval &RHS = li_->getInterval(isExtSubReg ? SrcReg : DstReg);
901 if (li_->hasInterval(PhysReg) &&
902 RHS.overlaps(li_->getInterval(PhysReg))) {
903 DOUT << "Interfere with register ";
904 DEBUG(li_->getInterval(PhysReg).print(DOUT, tri_));
905 return false; // Not coalescable
907 for (const unsigned* SR = tri_->getSubRegisters(PhysReg); *SR; ++SR)
908 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
909 DOUT << "Interfere with sub-register ";
910 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
911 return false; // Not coalescable
915 unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
916 : CopyMI->getOperand(2).getSubReg();
918 if (OldSubIdx == SubIdx)
919 // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
920 // coalesced to a larger register so the subreg indices cancel out.
923 DOUT << "\t Sub-register indices mismatch.\n";
924 return false; // Not coalescable.
928 unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
929 unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
930 unsigned LargeRegSize =
931 li_->getInterval(LargeReg).getSize() / InstrSlots::NUM;
932 unsigned SmallRegSize =
933 li_->getInterval(SmallReg).getSize() / InstrSlots::NUM;
934 const TargetRegisterClass *RC = mri_->getRegClass(SmallReg);
935 unsigned Threshold = allocatableRCRegs_[RC].count();
936 // Be conservative. If both sides are virtual registers, do not coalesce
937 // if this will cause a high use density interval to target a smaller
939 if (SmallRegSize > Threshold || LargeRegSize > Threshold) {
940 LiveVariables::VarInfo &svi = lv_->getVarInfo(LargeReg);
941 LiveVariables::VarInfo &dvi = lv_->getVarInfo(SmallReg);
942 if ((float)dvi.NumUses / SmallRegSize <
943 (float)svi.NumUses / LargeRegSize) {
944 Again = true; // May be possible to coalesce later.
950 } else if (differingRegisterClasses(SrcReg, DstReg)) {
951 // FIXME: What if the resul of a EXTRACT_SUBREG is then coalesced
952 // with another? If it's the resulting destination register, then
953 // the subidx must be propagated to uses (but only those defined
954 // by the EXTRACT_SUBREG). If it's being coalesced into another
955 // register, it should be safe because register is assumed to have
956 // the register class of the super-register.
958 // If they are not of the same register class, we cannot join them.
959 DOUT << "\tSrc/Dest are different register classes.\n";
960 // Allow the coalescer to try again in case either side gets coalesced to
961 // a physical register that's compatible with the other side. e.g.
962 // r1024 = MOV32to32_ r1025
963 // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
964 Again = true; // May be possible to coalesce later.
968 LiveInterval &SrcInt = li_->getInterval(SrcReg);
969 LiveInterval &DstInt = li_->getInterval(DstReg);
970 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
971 "Register mapping is horribly broken!");
973 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
974 DOUT << " and "; DstInt.print(DOUT, tri_);
977 // Check if it is necessary to propagate "isDead" property.
978 if (!isExtSubReg && !isInsSubReg) {
979 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
980 bool isDead = mopd->isDead();
982 // We need to be careful about coalescing a source physical register with a
983 // virtual register. Once the coalescing is done, it cannot be broken and
984 // these are not spillable! If the destination interval uses are far away,
985 // think twice about coalescing them!
986 if (!isDead && (SrcIsPhys || DstIsPhys)) {
987 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
988 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
989 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
990 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
991 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
992 if (TheCopy.isBackEdge)
993 Threshold *= 2; // Favors back edge copies.
995 // If the virtual register live interval is long but it has low use desity,
996 // do not join them, instead mark the physical register as its allocation
998 unsigned Length = JoinVInt.getSize() / InstrSlots::NUM;
999 LiveVariables::VarInfo &vi = lv_->getVarInfo(JoinVReg);
1000 if (Length > Threshold &&
1001 (((float)vi.NumUses / Length) < (1.0 / Threshold))) {
1002 JoinVInt.preference = JoinPReg;
1004 DOUT << "\tMay tie down a physical register, abort!\n";
1005 Again = true; // May be possible to coalesce later.
1011 // Okay, attempt to join these two intervals. On failure, this returns false.
1012 // Otherwise, if one of the intervals being joined is a physreg, this method
1013 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1014 // been modified, so we can use this information below to update aliases.
1015 bool Swapped = false;
1016 // If SrcInt is implicitly defined, it's safe to coalesce.
1017 bool isEmpty = SrcInt.empty();
1018 if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
1019 // Only coalesce an empty interval (defined by implicit_def) with
1020 // another interval which has a valno defined by the CopyMI and the CopyMI
1021 // is a kill of the implicit def.
1022 DOUT << "Not profitable!\n";
1026 if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
1027 // Coalescing failed.
1029 // If we can eliminate the copy without merging the live ranges, do so now.
1030 if (!isExtSubReg && !isInsSubReg &&
1031 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1032 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
1033 JoinedCopies.insert(CopyMI);
1037 // Otherwise, we are unable to join the intervals.
1038 DOUT << "Interference!\n";
1039 Again = true; // May be possible to coalesce later.
1043 LiveInterval *ResSrcInt = &SrcInt;
1044 LiveInterval *ResDstInt = &DstInt;
1046 std::swap(SrcReg, DstReg);
1047 std::swap(ResSrcInt, ResDstInt);
1049 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1050 "LiveInterval::join didn't work right!");
1052 // If we're about to merge live ranges into a physical register live range,
1053 // we have to update any aliased register's live ranges to indicate that they
1054 // have clobbered values for this range.
1055 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1056 // If this is a extract_subreg where dst is a physical register, e.g.
1057 // cl = EXTRACT_SUBREG reg1024, 1
1058 // then create and update the actual physical register allocated to RHS.
1059 if (RealDstReg || RealSrcReg) {
1060 LiveInterval &RealInt =
1061 li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
1062 SmallSet<const VNInfo*, 4> CopiedValNos;
1063 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
1064 E = ResSrcInt->ranges.end(); I != E; ++I) {
1065 const LiveRange *DstLR = ResDstInt->getLiveRangeContaining(I->start);
1066 assert(DstLR && "Invalid joined interval!");
1067 const VNInfo *DstValNo = DstLR->valno;
1068 if (CopiedValNos.insert(DstValNo)) {
1069 VNInfo *ValNo = RealInt.getNextValue(DstValNo->def, DstValNo->copy,
1070 li_->getVNInfoAllocator());
1071 ValNo->hasPHIKill = DstValNo->hasPHIKill;
1072 RealInt.addKills(ValNo, DstValNo->kills);
1073 RealInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
1077 DstReg = RealDstReg ? RealDstReg : RealSrcReg;
1080 // Update the liveintervals of sub-registers.
1081 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
1082 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
1083 li_->getVNInfoAllocator());
1085 // Merge use info if the destination is a virtual register.
1086 LiveVariables::VarInfo& dVI = lv_->getVarInfo(DstReg);
1087 LiveVariables::VarInfo& sVI = lv_->getVarInfo(SrcReg);
1088 dVI.NumUses += sVI.NumUses;
1091 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1092 // larger super-register.
1093 if ((isExtSubReg || isInsSubReg) && !SrcIsPhys && !DstIsPhys) {
1094 if ((isExtSubReg && !Swapped) || (isInsSubReg && Swapped)) {
1095 ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
1096 std::swap(SrcReg, DstReg);
1097 std::swap(ResSrcInt, ResDstInt);
1102 // Add all copies that define val# in the source interval into the queue.
1103 for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
1104 e = ResSrcInt->vni_end(); i != e; ++i) {
1105 const VNInfo *vni = *i;
1106 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
1108 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
1109 unsigned NewSrcReg, NewDstReg;
1111 JoinedCopies.count(CopyMI) == 0 &&
1112 tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg)) {
1113 unsigned LoopDepth = loopInfo->getLoopDepth(CopyMI->getParent());
1114 JoinQueue->push(CopyRec(CopyMI, LoopDepth,
1115 isBackEdgeCopy(CopyMI, DstReg)));
1120 // Remember to delete the copy instruction.
1121 JoinedCopies.insert(CopyMI);
1123 // Some live range has been lengthened due to colaescing, eliminate the
1124 // unnecessary kills.
1125 RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1126 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1127 RemoveUnnecessaryKills(DstReg, *ResDstInt);
1129 // SrcReg is guarateed to be the register whose live interval that is
1131 li_->removeInterval(SrcReg);
1135 // r1024 = implicit_def
1138 RemoveDeadImpDef(DstReg, *ResDstInt);
1139 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1142 // Now the copy is being coalesced away, the val# previously defined
1143 // by the copy is being defined by an IMPLICIT_DEF which defines a zero
1144 // length interval. Remove the val#.
1145 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1146 const LiveRange *LR = ResDstInt->getLiveRangeContaining(CopyIdx);
1147 VNInfo *ImpVal = LR->valno;
1148 assert(ImpVal->def == CopyIdx);
1149 unsigned NextDef = LR->end;
1150 RemoveCopiesFromValNo(*ResDstInt, ImpVal);
1151 ResDstInt->removeValNo(ImpVal);
1152 LR = ResDstInt->FindLiveRangeContaining(NextDef);
1153 if (LR != ResDstInt->end() && LR->valno->def == NextDef) {
1154 // Special case: vr1024 = implicit_def
1155 // vr1024 = insert_subreg vr1024, vr1025, c
1156 // The insert_subreg becomes a "copy" that defines a val# which can itself
1157 // be coalesced away.
1158 MachineInstr *DefMI = li_->getInstructionFromIndex(NextDef);
1159 if (DefMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
1160 LR->valno->copy = DefMI;
1164 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, tri_);
1171 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1172 /// compute what the resultant value numbers for each value in the input two
1173 /// ranges will be. This is complicated by copies between the two which can
1174 /// and will commonly cause multiple value numbers to be merged into one.
1176 /// VN is the value number that we're trying to resolve. InstDefiningValue
1177 /// keeps track of the new InstDefiningValue assignment for the result
1178 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1179 /// whether a value in this or other is a copy from the opposite set.
1180 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1181 /// already been assigned.
1183 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1184 /// contains the value number the copy is from.
1186 static unsigned ComputeUltimateVN(VNInfo *VNI,
1187 SmallVector<VNInfo*, 16> &NewVNInfo,
1188 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1189 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1190 SmallVector<int, 16> &ThisValNoAssignments,
1191 SmallVector<int, 16> &OtherValNoAssignments) {
1192 unsigned VN = VNI->id;
1194 // If the VN has already been computed, just return it.
1195 if (ThisValNoAssignments[VN] >= 0)
1196 return ThisValNoAssignments[VN];
1197 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
1199 // If this val is not a copy from the other val, then it must be a new value
1200 // number in the destination.
1201 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1202 if (I == ThisFromOther.end()) {
1203 NewVNInfo.push_back(VNI);
1204 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1206 VNInfo *OtherValNo = I->second;
1208 // Otherwise, this *is* a copy from the RHS. If the other side has already
1209 // been computed, return it.
1210 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1211 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1213 // Mark this value number as currently being computed, then ask what the
1214 // ultimate value # of the other value is.
1215 ThisValNoAssignments[VN] = -2;
1216 unsigned UltimateVN =
1217 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1218 OtherValNoAssignments, ThisValNoAssignments);
1219 return ThisValNoAssignments[VN] = UltimateVN;
1222 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
1223 return std::find(V.begin(), V.end(), Val) != V.end();
1226 /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1227 /// the specified live interval is defined by a copy from the specified
1229 bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1232 unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1235 if (LR->valno->def == ~0U &&
1236 TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1237 *tri_->getSuperRegisters(li.reg)) {
1238 // It's a sub-register live interval, we may not have precise information.
1240 MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1241 unsigned SrcReg, DstReg;
1242 if (tii_->isMoveInstr(*DefMI, SrcReg, DstReg) &&
1243 DstReg == li.reg && SrcReg == Reg) {
1244 // Cache computed info.
1245 LR->valno->def = LR->start;
1246 LR->valno->copy = DefMI;
1253 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1254 /// caller of this method must guarantee that the RHS only contains a single
1255 /// value number and that the RHS is not defined by a copy from this
1256 /// interval. This returns false if the intervals are not joinable, or it
1257 /// joins them and returns true.
1258 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
1259 assert(RHS.containsOneValue());
1261 // Some number (potentially more than one) value numbers in the current
1262 // interval may be defined as copies from the RHS. Scan the overlapping
1263 // portions of the LHS and RHS, keeping track of this and looking for
1264 // overlapping live ranges that are NOT defined as copies. If these exist, we
1267 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1268 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1270 if (LHSIt->start < RHSIt->start) {
1271 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1272 if (LHSIt != LHS.begin()) --LHSIt;
1273 } else if (RHSIt->start < LHSIt->start) {
1274 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1275 if (RHSIt != RHS.begin()) --RHSIt;
1278 SmallVector<VNInfo*, 8> EliminatedLHSVals;
1281 // Determine if these live intervals overlap.
1282 bool Overlaps = false;
1283 if (LHSIt->start <= RHSIt->start)
1284 Overlaps = LHSIt->end > RHSIt->start;
1286 Overlaps = RHSIt->end > LHSIt->start;
1288 // If the live intervals overlap, there are two interesting cases: if the
1289 // LHS interval is defined by a copy from the RHS, it's ok and we record
1290 // that the LHS value # is the same as the RHS. If it's not, then we cannot
1291 // coalesce these live ranges and we bail out.
1293 // If we haven't already recorded that this value # is safe, check it.
1294 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
1295 // Copy from the RHS?
1296 if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
1297 return false; // Nope, bail out.
1299 EliminatedLHSVals.push_back(LHSIt->valno);
1302 // We know this entire LHS live range is okay, so skip it now.
1303 if (++LHSIt == LHSEnd) break;
1307 if (LHSIt->end < RHSIt->end) {
1308 if (++LHSIt == LHSEnd) break;
1310 // One interesting case to check here. It's possible that we have
1311 // something like "X3 = Y" which defines a new value number in the LHS,
1312 // and is the last use of this liverange of the RHS. In this case, we
1313 // want to notice this copy (so that it gets coalesced away) even though
1314 // the live ranges don't actually overlap.
1315 if (LHSIt->start == RHSIt->end) {
1316 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
1317 // We already know that this value number is going to be merged in
1318 // if coalescing succeeds. Just skip the liverange.
1319 if (++LHSIt == LHSEnd) break;
1321 // Otherwise, if this is a copy from the RHS, mark it as being merged
1323 if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
1324 EliminatedLHSVals.push_back(LHSIt->valno);
1326 // We know this entire LHS live range is okay, so skip it now.
1327 if (++LHSIt == LHSEnd) break;
1332 if (++RHSIt == RHSEnd) break;
1336 // If we got here, we know that the coalescing will be successful and that
1337 // the value numbers in EliminatedLHSVals will all be merged together. Since
1338 // the most common case is that EliminatedLHSVals has a single number, we
1339 // optimize for it: if there is more than one value, we merge them all into
1340 // the lowest numbered one, then handle the interval as if we were merging
1341 // with one value number.
1343 if (EliminatedLHSVals.size() > 1) {
1344 // Loop through all the equal value numbers merging them into the smallest
1346 VNInfo *Smallest = EliminatedLHSVals[0];
1347 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1348 if (EliminatedLHSVals[i]->id < Smallest->id) {
1349 // Merge the current notion of the smallest into the smaller one.
1350 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1351 Smallest = EliminatedLHSVals[i];
1353 // Merge into the smallest.
1354 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1357 LHSValNo = Smallest;
1358 } else if (EliminatedLHSVals.empty()) {
1359 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1360 *tri_->getSuperRegisters(LHS.reg))
1361 // Imprecise sub-register information. Can't handle it.
1363 assert(0 && "No copies from the RHS?");
1365 LHSValNo = EliminatedLHSVals[0];
1368 // Okay, now that there is a single LHS value number that we're merging the
1369 // RHS into, update the value number info for the LHS to indicate that the
1370 // value number is defined where the RHS value number was.
1371 const VNInfo *VNI = RHS.getValNumInfo(0);
1372 LHSValNo->def = VNI->def;
1373 LHSValNo->copy = VNI->copy;
1375 // Okay, the final step is to loop over the RHS live intervals, adding them to
1377 LHSValNo->hasPHIKill |= VNI->hasPHIKill;
1378 LHS.addKills(LHSValNo, VNI->kills);
1379 LHS.MergeRangesInAsValue(RHS, LHSValNo);
1380 LHS.weight += RHS.weight;
1381 if (RHS.preference && !LHS.preference)
1382 LHS.preference = RHS.preference;
1387 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1388 /// returns false. Otherwise, if one of the intervals being joined is a
1389 /// physreg, this method always canonicalizes LHS to be it. The output
1390 /// "RHS" will not have been modified, so we can use this information
1391 /// below to update aliases.
1392 bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
1393 LiveInterval &RHS, bool &Swapped) {
1394 // Compute the final value assignment, assuming that the live ranges can be
1396 SmallVector<int, 16> LHSValNoAssignments;
1397 SmallVector<int, 16> RHSValNoAssignments;
1398 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1399 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1400 SmallVector<VNInfo*, 16> NewVNInfo;
1402 // If a live interval is a physical register, conservatively check if any
1403 // of its sub-registers is overlapping the live interval of the virtual
1404 // register. If so, do not coalesce.
1405 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1406 *tri_->getSubRegisters(LHS.reg)) {
1407 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
1408 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1409 DOUT << "Interfere with sub-register ";
1410 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1413 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1414 *tri_->getSubRegisters(RHS.reg)) {
1415 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
1416 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1417 DOUT << "Interfere with sub-register ";
1418 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1423 // Compute ultimate value numbers for the LHS and RHS values.
1424 if (RHS.containsOneValue()) {
1425 // Copies from a liveinterval with a single value are simple to handle and
1426 // very common, handle the special case here. This is important, because
1427 // often RHS is small and LHS is large (e.g. a physreg).
1429 // Find out if the RHS is defined as a copy from some value in the LHS.
1430 int RHSVal0DefinedFromLHS = -1;
1432 VNInfo *RHSValNoInfo = NULL;
1433 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
1434 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
1435 if ((RHSSrcReg == 0 || RHSSrcReg != LHS.reg)) {
1436 // If RHS is not defined as a copy from the LHS, we can use simpler and
1437 // faster checks to see if the live ranges are coalescable. This joiner
1438 // can't swap the LHS/RHS intervals though.
1439 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1440 return SimpleJoin(LHS, RHS);
1442 RHSValNoInfo = RHSValNoInfo0;
1445 // It was defined as a copy from the LHS, find out what value # it is.
1446 RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
1447 RHSValID = RHSValNoInfo->id;
1448 RHSVal0DefinedFromLHS = RHSValID;
1451 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1452 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1453 NewVNInfo.resize(LHS.getNumValNums(), NULL);
1455 // Okay, *all* of the values in LHS that are defined as a copy from RHS
1456 // should now get updated.
1457 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1460 unsigned VN = VNI->id;
1461 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1462 if (LHSSrcReg != RHS.reg) {
1463 // If this is not a copy from the RHS, its value number will be
1464 // unmodified by the coalescing.
1465 NewVNInfo[VN] = VNI;
1466 LHSValNoAssignments[VN] = VN;
1467 } else if (RHSValID == -1) {
1468 // Otherwise, it is a copy from the RHS, and we don't already have a
1469 // value# for it. Keep the current value number, but remember it.
1470 LHSValNoAssignments[VN] = RHSValID = VN;
1471 NewVNInfo[VN] = RHSValNoInfo;
1472 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1474 // Otherwise, use the specified value #.
1475 LHSValNoAssignments[VN] = RHSValID;
1476 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
1477 NewVNInfo[VN] = RHSValNoInfo;
1478 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1482 NewVNInfo[VN] = VNI;
1483 LHSValNoAssignments[VN] = VN;
1487 assert(RHSValID != -1 && "Didn't find value #?");
1488 RHSValNoAssignments[0] = RHSValID;
1489 if (RHSVal0DefinedFromLHS != -1) {
1490 // This path doesn't go through ComputeUltimateVN so just set
1492 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
1495 // Loop over the value numbers of the LHS, seeing if any are defined from
1497 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1500 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
1503 // DstReg is known to be a register in the LHS interval. If the src is
1504 // from the RHS interval, we can use its value #.
1505 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
1508 // Figure out the value # from the RHS.
1509 LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
1512 // Loop over the value numbers of the RHS, seeing if any are defined from
1514 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1517 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
1520 // DstReg is known to be a register in the RHS interval. If the src is
1521 // from the LHS interval, we can use its value #.
1522 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
1525 // Figure out the value # from the LHS.
1526 RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
1529 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1530 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1531 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1533 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1536 unsigned VN = VNI->id;
1537 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1539 ComputeUltimateVN(VNI, NewVNInfo,
1540 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1541 LHSValNoAssignments, RHSValNoAssignments);
1543 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1546 unsigned VN = VNI->id;
1547 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1549 // If this value number isn't a copy from the LHS, it's a new number.
1550 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1551 NewVNInfo.push_back(VNI);
1552 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1556 ComputeUltimateVN(VNI, NewVNInfo,
1557 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1558 RHSValNoAssignments, LHSValNoAssignments);
1562 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1563 // interval lists to see if these intervals are coalescable.
1564 LiveInterval::const_iterator I = LHS.begin();
1565 LiveInterval::const_iterator IE = LHS.end();
1566 LiveInterval::const_iterator J = RHS.begin();
1567 LiveInterval::const_iterator JE = RHS.end();
1569 // Skip ahead until the first place of potential sharing.
1570 if (I->start < J->start) {
1571 I = std::upper_bound(I, IE, J->start);
1572 if (I != LHS.begin()) --I;
1573 } else if (J->start < I->start) {
1574 J = std::upper_bound(J, JE, I->start);
1575 if (J != RHS.begin()) --J;
1579 // Determine if these two live ranges overlap.
1581 if (I->start < J->start) {
1582 Overlaps = I->end > J->start;
1584 Overlaps = J->end > I->start;
1587 // If so, check value # info to determine if they are really different.
1589 // If the live range overlap will map to the same value number in the
1590 // result liverange, we can still coalesce them. If not, we can't.
1591 if (LHSValNoAssignments[I->valno->id] !=
1592 RHSValNoAssignments[J->valno->id])
1596 if (I->end < J->end) {
1605 // Update kill info. Some live ranges are extended due to copy coalescing.
1606 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1607 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1608 VNInfo *VNI = I->first;
1609 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1610 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
1611 NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
1612 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
1615 // Update kill info. Some live ranges are extended due to copy coalescing.
1616 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1617 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1618 VNInfo *VNI = I->first;
1619 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1620 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
1621 NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
1622 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
1625 // If we get here, we know that we can coalesce the live ranges. Ask the
1626 // intervals to coalesce themselves now.
1627 if ((RHS.ranges.size() > LHS.ranges.size() &&
1628 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
1629 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1630 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
1633 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
1640 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1641 // depth of the basic block (the unsigned), and then on the MBB number.
1642 struct DepthMBBCompare {
1643 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1644 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1645 if (LHS.first > RHS.first) return true; // Deeper loops first
1646 return LHS.first == RHS.first &&
1647 LHS.second->getNumber() < RHS.second->getNumber();
1652 /// getRepIntervalSize - Returns the size of the interval that represents the
1653 /// specified register.
1655 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
1656 return Rc->getRepIntervalSize(Reg);
1659 /// CopyRecSort::operator - Join priority queue sorting function.
1661 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
1662 // Inner loops first.
1663 if (left.LoopDepth > right.LoopDepth)
1665 else if (left.LoopDepth == right.LoopDepth)
1666 if (left.isBackEdge && !right.isBackEdge)
1671 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1672 std::vector<CopyRec> &TryAgain) {
1673 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
1675 std::vector<CopyRec> VirtCopies;
1676 std::vector<CopyRec> PhysCopies;
1677 std::vector<CopyRec> ImpDefCopies;
1678 unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
1679 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1681 MachineInstr *Inst = MII++;
1683 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1684 unsigned SrcReg, DstReg;
1685 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1686 DstReg = Inst->getOperand(0).getReg();
1687 SrcReg = Inst->getOperand(1).getReg();
1688 } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
1689 DstReg = Inst->getOperand(0).getReg();
1690 SrcReg = Inst->getOperand(2).getReg();
1691 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
1694 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1695 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1697 JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
1699 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1700 ImpDefCopies.push_back(CopyRec(Inst, 0, false));
1701 else if (SrcIsPhys || DstIsPhys)
1702 PhysCopies.push_back(CopyRec(Inst, 0, false));
1704 VirtCopies.push_back(CopyRec(Inst, 0, false));
1711 // Try coalescing implicit copies first, followed by copies to / from
1712 // physical registers, then finally copies from virtual registers to
1713 // virtual registers.
1714 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1715 CopyRec &TheCopy = ImpDefCopies[i];
1717 if (!JoinCopy(TheCopy, Again))
1719 TryAgain.push_back(TheCopy);
1721 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1722 CopyRec &TheCopy = PhysCopies[i];
1724 if (!JoinCopy(TheCopy, Again))
1726 TryAgain.push_back(TheCopy);
1728 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1729 CopyRec &TheCopy = VirtCopies[i];
1731 if (!JoinCopy(TheCopy, Again))
1733 TryAgain.push_back(TheCopy);
1737 void SimpleRegisterCoalescing::joinIntervals() {
1738 DOUT << "********** JOINING INTERVALS ***********\n";
1741 JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
1743 std::vector<CopyRec> TryAgainList;
1744 if (loopInfo->begin() == loopInfo->end()) {
1745 // If there are no loops in the function, join intervals in function order.
1746 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1748 CopyCoalesceInMBB(I, TryAgainList);
1750 // Otherwise, join intervals in inner loops before other intervals.
1751 // Unfortunately we can't just iterate over loop hierarchy here because
1752 // there may be more MBB's than BB's. Collect MBB's for sorting.
1754 // Join intervals in the function prolog first. We want to join physical
1755 // registers with virtual registers before the intervals got too long.
1756 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1757 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1758 MachineBasicBlock *MBB = I;
1759 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1762 // Sort by loop depth.
1763 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1765 // Finally, join intervals in loop nest order.
1766 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1767 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1770 // Joining intervals can allow other intervals to be joined. Iteratively join
1771 // until we make no progress.
1773 SmallVector<CopyRec, 16> TryAgain;
1774 bool ProgressMade = true;
1775 while (ProgressMade) {
1776 ProgressMade = false;
1777 while (!JoinQueue->empty()) {
1778 CopyRec R = JoinQueue->pop();
1780 bool Success = JoinCopy(R, Again);
1782 ProgressMade = true;
1784 TryAgain.push_back(R);
1788 while (!TryAgain.empty()) {
1789 JoinQueue->push(TryAgain.back());
1790 TryAgain.pop_back();
1795 bool ProgressMade = true;
1796 while (ProgressMade) {
1797 ProgressMade = false;
1799 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1800 CopyRec &TheCopy = TryAgainList[i];
1803 bool Success = JoinCopy(TheCopy, Again);
1804 if (Success || !Again) {
1805 TheCopy.MI = 0; // Mark this one as done.
1806 ProgressMade = true;
1817 /// Return true if the two specified registers belong to different register
1818 /// classes. The registers may be either phys or virt regs.
1819 bool SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1820 unsigned RegB) const {
1822 // Get the register classes for the first reg.
1823 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1824 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1825 "Shouldn't consider two physregs!");
1826 return !mri_->getRegClass(RegB)->contains(RegA);
1829 // Compare against the regclass for the second reg.
1830 const TargetRegisterClass *RegClass = mri_->getRegClass(RegA);
1831 if (TargetRegisterInfo::isVirtualRegister(RegB))
1832 return RegClass != mri_->getRegClass(RegB);
1834 return !RegClass->contains(RegB);
1837 /// lastRegisterUse - Returns the last use of the specific register between
1838 /// cycles Start and End or NULL if there are no uses.
1840 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
1841 unsigned Reg, unsigned &UseIdx) const{
1843 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1844 MachineOperand *LastUse = NULL;
1845 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
1846 E = mri_->use_end(); I != E; ++I) {
1847 MachineOperand &Use = I.getOperand();
1848 MachineInstr *UseMI = Use.getParent();
1849 unsigned SrcReg, DstReg;
1850 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg) && SrcReg == DstReg)
1851 // Ignore identity copies.
1853 unsigned Idx = li_->getInstructionIndex(UseMI);
1854 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1862 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1865 // Skip deleted instructions
1866 MachineInstr *MI = li_->getInstructionFromIndex(e);
1867 while ((e - InstrSlots::NUM) >= s && !MI) {
1868 e -= InstrSlots::NUM;
1869 MI = li_->getInstructionFromIndex(e);
1871 if (e < s || MI == NULL)
1874 // Ignore identity copies.
1875 unsigned SrcReg, DstReg;
1876 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg))
1877 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1878 MachineOperand &Use = MI->getOperand(i);
1879 if (Use.isRegister() && Use.isUse() && Use.getReg() &&
1880 tri_->regsOverlap(Use.getReg(), Reg)) {
1886 e -= InstrSlots::NUM;
1893 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
1894 if (TargetRegisterInfo::isPhysicalRegister(reg))
1895 cerr << tri_->getName(reg);
1897 cerr << "%reg" << reg;
1900 void SimpleRegisterCoalescing::releaseMemory() {
1901 JoinedCopies.clear();
1904 static bool isZeroLengthInterval(LiveInterval *li) {
1905 for (LiveInterval::Ranges::const_iterator
1906 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
1907 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
1912 /// TurnCopyIntoImpDef - If source of the specified copy is an implicit def,
1913 /// turn the copy into an implicit def.
1915 SimpleRegisterCoalescing::TurnCopyIntoImpDef(MachineBasicBlock::iterator &I,
1916 MachineBasicBlock *MBB,
1917 unsigned DstReg, unsigned SrcReg) {
1918 MachineInstr *CopyMI = &*I;
1919 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1920 if (!li_->hasInterval(SrcReg))
1922 LiveInterval &SrcInt = li_->getInterval(SrcReg);
1923 if (!SrcInt.empty())
1925 if (!li_->hasInterval(DstReg))
1927 LiveInterval &DstInt = li_->getInterval(DstReg);
1928 const LiveRange *DstLR = DstInt.getLiveRangeContaining(CopyIdx);
1929 DstInt.removeValNo(DstLR->valno);
1930 CopyMI->setDesc(tii_->get(TargetInstrInfo::IMPLICIT_DEF));
1931 for (int i = CopyMI->getNumOperands() - 1, e = 0; i > e; --i)
1932 CopyMI->RemoveOperand(i);
1933 bool NoUse = mri_->use_begin(SrcReg) == mri_->use_end();
1935 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
1936 E = mri_->reg_end(); I != E; ) {
1937 assert(I.getOperand().isDef());
1938 MachineInstr *DefMI = &*I;
1940 // The implicit_def source has no other uses, delete it.
1941 assert(DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF);
1942 li_->RemoveMachineInstrFromMaps(DefMI);
1943 DefMI->eraseFromParent();
1951 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1953 mri_ = &fn.getRegInfo();
1954 tm_ = &fn.getTarget();
1955 tri_ = tm_->getRegisterInfo();
1956 tii_ = tm_->getInstrInfo();
1957 li_ = &getAnalysis<LiveIntervals>();
1958 lv_ = &getAnalysis<LiveVariables>();
1959 loopInfo = &getAnalysis<MachineLoopInfo>();
1961 DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
1962 << "********** Function: "
1963 << ((Value*)mf_->getFunction())->getName() << '\n';
1965 allocatableRegs_ = tri_->getAllocatableSet(fn);
1966 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1967 E = tri_->regclass_end(); I != E; ++I)
1968 allocatableRCRegs_.insert(std::make_pair(*I,
1969 tri_->getAllocatableSet(fn, *I)));
1971 // Join (coalesce) intervals if requested.
1972 if (EnableJoining) {
1974 DOUT << "********** INTERVALS POST JOINING **********\n";
1975 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
1976 I->second.print(DOUT, tri_);
1980 // Delete all coalesced copies.
1981 for (SmallPtrSet<MachineInstr*,32>::iterator I = JoinedCopies.begin(),
1982 E = JoinedCopies.end(); I != E; ++I) {
1983 MachineInstr *CopyMI = *I;
1984 unsigned SrcReg, DstReg;
1985 if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
1986 assert((CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
1987 CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) &&
1988 "Unrecognized copy instruction");
1989 DstReg = CopyMI->getOperand(0).getReg();
1991 if (CopyMI->registerDefIsDead(DstReg)) {
1992 LiveInterval &li = li_->getInterval(DstReg);
1993 if (!ShortenDeadCopySrcLiveRange(li, CopyMI))
1994 ShortenDeadCopyLiveRange(li, CopyMI);
1996 li_->RemoveMachineInstrFromMaps(*I);
1997 (*I)->eraseFromParent();
2002 // Perform a final pass over the instructions and compute spill weights
2003 // and remove identity moves.
2004 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2005 mbbi != mbbe; ++mbbi) {
2006 MachineBasicBlock* mbb = mbbi;
2007 unsigned loopDepth = loopInfo->getLoopDepth(mbb);
2009 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2011 // if the move will be an identity move delete it
2012 unsigned srcReg, dstReg;
2013 bool isMove = tii_->isMoveInstr(*mii, srcReg, dstReg);
2014 if (isMove && srcReg == dstReg) {
2015 if (li_->hasInterval(srcReg)) {
2016 LiveInterval &RegInt = li_->getInterval(srcReg);
2017 // If def of this move instruction is dead, remove its live range
2018 // from the dstination register's live interval.
2019 if (mii->registerDefIsDead(dstReg)) {
2020 if (!ShortenDeadCopySrcLiveRange(RegInt, mii))
2021 ShortenDeadCopyLiveRange(RegInt, mii);
2024 li_->RemoveMachineInstrFromMaps(mii);
2025 mii = mbbi->erase(mii);
2027 } else if (!isMove || !TurnCopyIntoImpDef(mii, mbb, dstReg, srcReg)) {
2028 SmallSet<unsigned, 4> UniqueUses;
2029 for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
2030 const MachineOperand &mop = mii->getOperand(i);
2031 if (mop.isRegister() && mop.getReg() &&
2032 TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
2033 unsigned reg = mop.getReg();
2034 // Multiple uses of reg by the same instruction. It should not
2035 // contribute to spill weight again.
2036 if (UniqueUses.count(reg) != 0)
2038 LiveInterval &RegInt = li_->getInterval(reg);
2040 li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
2041 UniqueUses.insert(reg);
2049 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
2050 LiveInterval &LI = I->second;
2051 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
2052 // If the live interval length is essentially zero, i.e. in every live
2053 // range the use follows def immediately, it doesn't make sense to spill
2054 // it and hope it will be easier to allocate for this li.
2055 if (isZeroLengthInterval(&LI))
2056 LI.weight = HUGE_VALF;
2058 bool isLoad = false;
2059 if (li_->isReMaterializable(LI, isLoad)) {
2060 // If all of the definitions of the interval are re-materializable,
2061 // it is a preferred candidate for spilling. If non of the defs are
2062 // loads, then it's potentially very cheap to re-materialize.
2063 // FIXME: this gets much more complicated once we support non-trivial
2064 // re-materialization.
2072 // Slightly prefer live interval that has been assigned a preferred reg.
2076 // Divide the weight of the interval by its size. This encourages
2077 // spilling of intervals that are large and have few uses, and
2078 // discourages spilling of small intervals with many uses.
2079 LI.weight /= LI.getSize();
2087 /// print - Implement the dump method.
2088 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
2092 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2093 return new SimpleRegisterCoalescing();
2096 // Make sure that anything that uses RegisterCoalescer pulls in this file...
2097 DEFINING_FILE_FOR(SimpleRegisterCoalescing)