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"),
57 CommuteDef("coalescer-commute-instrs",
58 cl::init(true), cl::Hidden);
61 CommuteLimit("commute-limit",
62 cl::init(-1), cl::Hidden);
64 RegisterPass<SimpleRegisterCoalescing>
65 X("simple-register-coalescing", "Simple Register Coalescing");
67 // Declare that we implement the RegisterCoalescer interface
68 RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
71 const PassInfo *llvm::SimpleRegisterCoalescingID = X.getPassInfo();
73 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
74 AU.addPreserved<LiveIntervals>();
75 AU.addPreserved<MachineLoopInfo>();
76 AU.addPreservedID(MachineDominatorsID);
77 AU.addPreservedID(PHIEliminationID);
78 AU.addPreservedID(TwoAddressInstructionPassID);
79 AU.addRequired<LiveVariables>();
80 AU.addRequired<LiveIntervals>();
81 AU.addRequired<MachineLoopInfo>();
82 MachineFunctionPass::getAnalysisUsage(AU);
85 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
86 /// being the source and IntB being the dest, thus this defines a value number
87 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
88 /// see if we can merge these two pieces of B into a single value number,
89 /// eliminating a copy. For example:
93 /// B1 = A3 <- this copy
95 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
96 /// value number to be replaced with B0 (which simplifies the B liveinterval).
98 /// This returns true if an interval was modified.
100 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
102 MachineInstr *CopyMI) {
103 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
105 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
106 // the example above.
107 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
108 VNInfo *BValNo = BLR->valno;
110 // Get the location that B is defined at. Two options: either this value has
111 // an unknown definition point or it is defined at CopyIdx. If unknown, we
113 if (!BValNo->copy) return false;
114 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
116 // AValNo is the value number in A that defines the copy, A3 in the example.
117 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
118 VNInfo *AValNo = ALR->valno;
120 // If AValNo is defined as a copy from IntB, we can potentially process this.
121 // Get the instruction that defines this value number.
122 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
123 if (!SrcReg) return false; // Not defined by a copy.
125 // If the value number is not defined by a copy instruction, ignore it.
127 // If the source register comes from an interval other than IntB, we can't
129 if (SrcReg != IntB.reg) return false;
131 // Get the LiveRange in IntB that this value number starts with.
132 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
134 // Make sure that the end of the live range is inside the same block as
136 MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
138 ValLREndInst->getParent() != CopyMI->getParent()) return false;
140 // Okay, we now know that ValLR ends in the same block that the CopyMI
141 // live-range starts. If there are no intervening live ranges between them in
142 // IntB, we can merge them.
143 if (ValLR+1 != BLR) return false;
145 // If a live interval is a physical register, conservatively check if any
146 // of its sub-registers is overlapping the live interval of the virtual
147 // register. If so, do not coalesce.
148 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
149 *tri_->getSubRegisters(IntB.reg)) {
150 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
151 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
152 DOUT << "Interfere with sub-register ";
153 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
158 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
160 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
161 // We are about to delete CopyMI, so need to remove it as the 'instruction
162 // that defines this value #'. Update the the valnum with the new defining
164 BValNo->def = FillerStart;
167 // Okay, we can merge them. We need to insert a new liverange:
168 // [ValLR.end, BLR.begin) of either value number, then we merge the
169 // two value numbers.
170 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
172 // If the IntB live range is assigned to a physical register, and if that
173 // physreg has aliases,
174 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
175 // Update the liveintervals of sub-registers.
176 for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) {
177 LiveInterval &AliasLI = li_->getInterval(*AS);
178 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
179 AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
183 // Okay, merge "B1" into the same value number as "B0".
184 if (BValNo != ValLR->valno)
185 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
186 DOUT << " result = "; IntB.print(DOUT, tri_);
189 // If the source instruction was killing the source register before the
190 // merge, unset the isKill marker given the live range has been extended.
191 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
193 ValLREndInst->getOperand(UIdx).setIsKill(false);
199 /// HasOtherReachingDefs - Return true if there are definitions of IntB
200 /// other than BValNo val# that can reach uses of AValno val# of IntA.
201 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
205 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
207 if (AI->valno != AValNo) continue;
208 LiveInterval::Ranges::iterator BI =
209 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
210 if (BI != IntB.ranges.begin())
212 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
213 if (BI->valno == BValNo)
215 if (BI->start <= AI->start && BI->end > AI->start)
217 if (BI->start > AI->start && BI->start < AI->end)
224 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
225 /// being the source and IntB being the dest, thus this defines a value number
226 /// in IntB. If the source value number (in IntA) is defined by a commutable
227 /// instruction and its other operand is coalesced to the copy dest register,
228 /// see if we can transform the copy into a noop by commuting the definition. For
231 /// A3 = op A2 B0<kill>
233 /// B1 = A3 <- this copy
235 /// = op A3 <- more uses
239 /// B2 = op B0 A2<kill>
241 /// B1 = B2 <- now an identify copy
243 /// = op B2 <- more uses
245 /// This returns true if an interval was modified.
247 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
249 MachineInstr *CopyMI) {
250 if (!CommuteDef) return false;
252 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
254 // FIXME: For now, only eliminate the copy by commuting its def when the
255 // source register is a virtual register. We want to guard against cases
256 // where the copy is a back edge copy and commuting the def lengthen the
257 // live interval of the source register to the entire loop.
258 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
261 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
262 // the example above.
263 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
264 VNInfo *BValNo = BLR->valno;
266 // Get the location that B is defined at. Two options: either this value has
267 // an unknown definition point or it is defined at CopyIdx. If unknown, we
269 if (!BValNo->copy) return false;
270 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
272 // AValNo is the value number in A that defines the copy, A3 in the example.
273 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
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 (CommuteLimit >= 0 && numCommutes >= (unsigned)CommuteLimit)
299 // At this point we have decided that it is legal to do this
300 // transformation. Start by commuting the instruction.
301 MachineBasicBlock *MBB = DefMI->getParent();
302 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
305 if (NewMI != DefMI) {
306 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
307 MBB->insert(DefMI, NewMI);
310 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
311 NewMI->getOperand(OpIdx).setIsKill();
313 // Update uses of IntA of the specific Val# with IntB.
314 bool BHasPHIKill = BValNo->hasPHIKill;
315 SmallVector<VNInfo*, 4> BDeadValNos;
316 SmallVector<unsigned, 4> BKills;
317 std::map<unsigned, unsigned> BExtend;
318 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
319 UE = mri_->use_end(); UI != UE;) {
320 MachineOperand &UseMO = UI.getOperand();
321 MachineInstr *UseMI = &*UI;
323 if (JoinedCopies.count(UseMI))
325 unsigned UseIdx = li_->getInstructionIndex(UseMI);
326 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
327 if (ULR->valno != AValNo)
329 UseMO.setReg(NewReg);
333 BKills.push_back(li_->getUseIndex(UseIdx)+1);
334 unsigned SrcReg, DstReg;
335 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg))
337 if (DstReg == IntB.reg) {
338 // This copy will become a noop. If it's defining a new val#,
339 // remove that val# as well. However this live range is being
340 // extended to the end of the existing live range defined by the copy.
341 unsigned DefIdx = li_->getDefIndex(UseIdx);
342 LiveInterval::iterator DLR = IntB.FindLiveRangeContaining(DefIdx);
343 BHasPHIKill |= DLR->valno->hasPHIKill;
344 assert(DLR->valno->def == DefIdx);
345 BDeadValNos.push_back(DLR->valno);
346 BExtend[DLR->start] = DLR->end;
347 JoinedCopies.insert(UseMI);
348 // If this is a kill but it's going to be removed, the last use
349 // of the same val# is the new kill.
350 if (UseMO.isKill()) {
356 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
357 // simply extend BLR if CopyMI doesn't end the range.
358 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
360 IntB.removeValNo(BValNo);
361 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
362 IntB.removeValNo(BDeadValNos[i]);
363 VNInfo *ValNo = IntB.getNextValue(ALR->start, 0, li_->getVNInfoAllocator());
364 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
366 if (AI->valno != AValNo) continue;
367 unsigned End = AI->end;
368 std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
369 if (EI != BExtend.end())
371 IntB.addRange(LiveRange(AI->start, End, ValNo));
373 IntB.addKills(ValNo, BKills);
374 ValNo->hasPHIKill = BHasPHIKill;
376 DOUT << " result = "; IntB.print(DOUT, tri_);
379 DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
380 IntA.removeValNo(AValNo);
381 DOUT << " result = "; IntA.print(DOUT, tri_);
388 /// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
390 bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
392 MachineBasicBlock *MBB = CopyMI->getParent();
393 const MachineLoop *L = loopInfo->getLoopFor(MBB);
396 if (MBB != L->getLoopLatch())
399 LiveInterval &LI = li_->getInterval(DstReg);
400 unsigned DefIdx = li_->getInstructionIndex(CopyMI);
401 LiveInterval::const_iterator DstLR =
402 LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
403 if (DstLR == LI.end())
405 unsigned KillIdx = li_->getInstructionIndex(&MBB->back()) + InstrSlots::NUM;
406 if (DstLR->valno->kills.size() == 1 &&
407 DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
412 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
413 /// update the subregister number if it is not zero. If DstReg is a
414 /// physical register and the existing subregister number of the def / use
415 /// being updated is not zero, make sure to set it to the correct physical
418 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
420 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
421 if (DstIsPhys && SubIdx) {
422 // Figure out the real physical register we are updating with.
423 DstReg = tri_->getSubReg(DstReg, SubIdx);
427 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
428 E = mri_->reg_end(); I != E; ) {
429 MachineOperand &O = I.getOperand();
432 unsigned UseSubIdx = O.getSubReg();
433 unsigned UseDstReg = DstReg;
435 UseDstReg = tri_->getSubReg(DstReg, UseSubIdx);
439 unsigned OldSubIdx = O.getSubReg();
440 // Sub-register indexes goes from small to large. e.g.
441 // RAX: 0 -> AL, 1 -> AH, 2 -> AX, 3 -> EAX
442 // EAX: 0 -> AL, 1 -> AH, 2 -> AX
443 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
444 // sub-register 2 is also AX.
445 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
446 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
454 /// ShortenDeadCopyLiveRange - Shorten a live range as it's artificially
455 /// extended by a dead copy. Mark the last use (if any) of the val# as kill
456 /// as ends the live range there. If there isn't another use, then this
457 /// live range is dead.
458 void SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
459 MachineInstr *CopyMI) {
460 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
461 LiveInterval::iterator MLR =
462 li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
463 unsigned RemoveStart = MLR->start;
464 unsigned RemoveEnd = MLR->end;
466 MachineOperand *LastUse = lastRegisterUse(RemoveStart, CopyIdx, li.reg,
469 // Shorten the liveinterval to the end of last use.
470 LastUse->setIsKill();
471 RemoveStart = li_->getDefIndex(LastUseIdx);
473 li.removeRange(RemoveStart, RemoveEnd, true);
475 li_->removeInterval(li.reg);
478 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
479 /// which are the src/dst of the copy instruction CopyMI. This returns true
480 /// if the copy was successfully coalesced away. If it is not currently
481 /// possible to coalesce this interval, but it may be possible if other
482 /// things get coalesced, then it returns true by reference in 'Again'.
483 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
484 MachineInstr *CopyMI = TheCopy.MI;
487 if (JoinedCopies.count(CopyMI))
488 return false; // Already done.
490 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
494 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
497 DstReg = CopyMI->getOperand(0).getReg();
498 SrcReg = CopyMI->getOperand(1).getReg();
499 } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
500 assert(0 && "Unrecognized copy instruction!");
504 // If they are already joined we continue.
505 if (SrcReg == DstReg) {
506 DOUT << "\tCopy already coalesced.\n";
507 return false; // Not coalescable.
510 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
511 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
513 // If they are both physical registers, we cannot join them.
514 if (SrcIsPhys && DstIsPhys) {
515 DOUT << "\tCan not coalesce physregs.\n";
516 return false; // Not coalescable.
519 // We only join virtual registers with allocatable physical registers.
520 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
521 DOUT << "\tSrc reg is unallocatable physreg.\n";
522 return false; // Not coalescable.
524 if (DstIsPhys && !allocatableRegs_[DstReg]) {
525 DOUT << "\tDst reg is unallocatable physreg.\n";
526 return false; // Not coalescable.
529 unsigned RealDstReg = 0;
531 SubIdx = CopyMI->getOperand(2).getImm();
533 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
534 // coalesced with AX.
535 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
537 } else if (DstIsPhys) {
538 // If this is a extract_subreg where dst is a physical register, e.g.
539 // cl = EXTRACT_SUBREG reg1024, 1
540 // then create and update the actual physical register allocated to RHS.
541 const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
542 for (const unsigned *SRs = tri_->getSuperRegisters(DstReg);
543 unsigned SR = *SRs; ++SRs) {
544 if (DstReg == tri_->getSubReg(SR, SubIdx) &&
550 assert(RealDstReg && "Invalid extra_subreg instruction!");
552 // For this type of EXTRACT_SUBREG, conservatively
553 // check if the live interval of the source register interfere with the
554 // actual super physical register we are trying to coalesce with.
555 LiveInterval &RHS = li_->getInterval(SrcReg);
556 if (li_->hasInterval(RealDstReg) &&
557 RHS.overlaps(li_->getInterval(RealDstReg))) {
558 DOUT << "Interfere with register ";
559 DEBUG(li_->getInterval(RealDstReg).print(DOUT, tri_));
560 return false; // Not coalescable
562 for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
563 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
564 DOUT << "Interfere with sub-register ";
565 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
566 return false; // Not coalescable
570 unsigned SrcSize= li_->getInterval(SrcReg).getSize() / InstrSlots::NUM;
571 unsigned DstSize= li_->getInterval(DstReg).getSize() / InstrSlots::NUM;
572 const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
573 unsigned Threshold = allocatableRCRegs_[RC].count();
574 // Be conservative. If both sides are virtual registers, do not coalesce
575 // if this will cause a high use density interval to target a smaller set
577 if (DstSize > Threshold || SrcSize > Threshold) {
578 LiveVariables::VarInfo &svi = lv_->getVarInfo(SrcReg);
579 LiveVariables::VarInfo &dvi = lv_->getVarInfo(DstReg);
580 if ((float)dvi.NumUses / DstSize < (float)svi.NumUses / SrcSize) {
581 Again = true; // May be possible to coalesce later.
586 } else if (differingRegisterClasses(SrcReg, DstReg)) {
587 // FIXME: What if the resul of a EXTRACT_SUBREG is then coalesced
588 // with another? If it's the resulting destination register, then
589 // the subidx must be propagated to uses (but only those defined
590 // by the EXTRACT_SUBREG). If it's being coalesced into another
591 // register, it should be safe because register is assumed to have
592 // the register class of the super-register.
594 // If they are not of the same register class, we cannot join them.
595 DOUT << "\tSrc/Dest are different register classes.\n";
596 // Allow the coalescer to try again in case either side gets coalesced to
597 // a physical register that's compatible with the other side. e.g.
598 // r1024 = MOV32to32_ r1025
599 // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
600 Again = true; // May be possible to coalesce later.
604 LiveInterval &SrcInt = li_->getInterval(SrcReg);
605 LiveInterval &DstInt = li_->getInterval(DstReg);
606 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
607 "Register mapping is horribly broken!");
609 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
610 DOUT << " and "; DstInt.print(DOUT, tri_);
613 // Check if it is necessary to propagate "isDead" property before intervals
615 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
616 bool isDead = mopd->isDead();
617 bool isShorten = false;
618 unsigned SrcStart = 0, RemoveStart = 0;
619 unsigned SrcEnd = 0, RemoveEnd = 0;
621 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
622 LiveInterval::iterator SrcLR =
623 SrcInt.FindLiveRangeContaining(li_->getUseIndex(CopyIdx));
624 RemoveStart = SrcStart = SrcLR->start;
625 RemoveEnd = SrcEnd = SrcLR->end;
626 if (SrcEnd > li_->getDefIndex(CopyIdx)) {
627 // If there are other uses of SrcReg beyond the copy, there is nothing to do.
631 MachineOperand *LastUse =
632 lastRegisterUse(SrcStart, CopyIdx, SrcReg, LastUseIdx);
634 // There are uses before the copy, just shorten the live range to the end
636 LastUse->setIsKill();
639 RemoveStart = li_->getDefIndex(LastUseIdx);
641 // This live range is truly dead. Remove it.
642 MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
643 if (SrcMI && SrcMI->modifiesRegister(SrcReg, tri_))
644 // A dead def should have a single cycle interval.
650 // We need to be careful about coalescing a source physical register with a
651 // virtual register. Once the coalescing is done, it cannot be broken and
652 // these are not spillable! If the destination interval uses are far away,
653 // think twice about coalescing them!
654 if (!mopd->isDead() && (SrcIsPhys || DstIsPhys) && !isExtSubReg) {
655 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
656 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
657 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
658 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
659 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
660 if (TheCopy.isBackEdge)
661 Threshold *= 2; // Favors back edge copies.
663 // If the virtual register live interval is long but it has low use desity,
664 // do not join them, instead mark the physical register as its allocation
666 unsigned Length = JoinVInt.getSize() / InstrSlots::NUM;
667 LiveVariables::VarInfo &vi = lv_->getVarInfo(JoinVReg);
668 if (Length > Threshold &&
669 (((float)vi.NumUses / Length) < (1.0 / Threshold))) {
670 JoinVInt.preference = JoinPReg;
672 DOUT << "\tMay tie down a physical register, abort!\n";
673 Again = true; // May be possible to coalesce later.
678 // Okay, attempt to join these two intervals. On failure, this returns false.
679 // Otherwise, if one of the intervals being joined is a physreg, this method
680 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
681 // been modified, so we can use this information below to update aliases.
682 bool Swapped = false;
683 if (JoinIntervals(DstInt, SrcInt, Swapped)) {
685 // Result of the copy is dead. Propagate this property.
687 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
688 "Live-in must be a physical register!");
689 // Live-in to the function but dead. Remove it from entry live-in set.
690 // JoinIntervals may end up swapping the two intervals.
691 mf_->begin()->removeLiveIn(SrcReg);
693 MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
695 int DeadIdx = SrcMI->findRegisterDefOperandIdx(SrcReg, false, tri_);
697 SrcMI->getOperand(DeadIdx).setIsDead();
702 if (isShorten || isDead) {
703 // Shorten the destination live interval.
705 SrcInt.removeRange(RemoveStart, RemoveEnd, true);
708 // Coalescing failed.
710 // If we can eliminate the copy without merging the live ranges, do so now.
712 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
713 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
714 JoinedCopies.insert(CopyMI);
718 // Otherwise, we are unable to join the intervals.
719 DOUT << "Interference!\n";
720 Again = true; // May be possible to coalesce later.
724 LiveInterval *ResSrcInt = &SrcInt;
725 LiveInterval *ResDstInt = &DstInt;
727 std::swap(SrcReg, DstReg);
728 std::swap(ResSrcInt, ResDstInt);
730 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
731 "LiveInterval::join didn't work right!");
733 // If we're about to merge live ranges into a physical register live range,
734 // we have to update any aliased register's live ranges to indicate that they
735 // have clobbered values for this range.
736 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
737 // If this is a extract_subreg where dst is a physical register, e.g.
738 // cl = EXTRACT_SUBREG reg1024, 1
739 // then create and update the actual physical register allocated to RHS.
741 LiveInterval &RealDstInt = li_->getOrCreateInterval(RealDstReg);
742 SmallSet<const VNInfo*, 4> CopiedValNos;
743 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
744 E = ResSrcInt->ranges.end(); I != E; ++I) {
745 LiveInterval::const_iterator DstLR =
746 ResDstInt->FindLiveRangeContaining(I->start);
747 assert(DstLR != ResDstInt->end() && "Invalid joined interval!");
748 const VNInfo *DstValNo = DstLR->valno;
749 if (CopiedValNos.insert(DstValNo)) {
750 VNInfo *ValNo = RealDstInt.getNextValue(DstValNo->def, DstValNo->copy,
751 li_->getVNInfoAllocator());
752 ValNo->hasPHIKill = DstValNo->hasPHIKill;
753 RealDstInt.addKills(ValNo, DstValNo->kills);
754 RealDstInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
760 // Update the liveintervals of sub-registers.
761 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
762 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
763 li_->getVNInfoAllocator());
765 // Merge use info if the destination is a virtual register.
766 LiveVariables::VarInfo& dVI = lv_->getVarInfo(DstReg);
767 LiveVariables::VarInfo& sVI = lv_->getVarInfo(SrcReg);
768 dVI.NumUses += sVI.NumUses;
771 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
772 // larger super-register.
773 if (isExtSubReg && !SrcIsPhys && !DstIsPhys) {
775 ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
776 std::swap(SrcReg, DstReg);
777 std::swap(ResSrcInt, ResDstInt);
782 // Add all copies that define val# in the source interval into the queue.
783 for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
784 e = ResSrcInt->vni_end(); i != e; ++i) {
785 const VNInfo *vni = *i;
786 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
788 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
789 unsigned NewSrcReg, NewDstReg;
791 JoinedCopies.count(CopyMI) == 0 &&
792 tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg)) {
793 unsigned LoopDepth = loopInfo->getLoopDepth(CopyMI->getParent());
794 JoinQueue->push(CopyRec(CopyMI, LoopDepth,
795 isBackEdgeCopy(CopyMI, DstReg)));
800 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, tri_);
803 // Remember to delete the copy instruction.
804 JoinedCopies.insert(CopyMI);
806 // SrcReg is guarateed to be the register whose live interval that is
808 li_->removeInterval(SrcReg);
809 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
815 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
816 /// compute what the resultant value numbers for each value in the input two
817 /// ranges will be. This is complicated by copies between the two which can
818 /// and will commonly cause multiple value numbers to be merged into one.
820 /// VN is the value number that we're trying to resolve. InstDefiningValue
821 /// keeps track of the new InstDefiningValue assignment for the result
822 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
823 /// whether a value in this or other is a copy from the opposite set.
824 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
825 /// already been assigned.
827 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
828 /// contains the value number the copy is from.
830 static unsigned ComputeUltimateVN(VNInfo *VNI,
831 SmallVector<VNInfo*, 16> &NewVNInfo,
832 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
833 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
834 SmallVector<int, 16> &ThisValNoAssignments,
835 SmallVector<int, 16> &OtherValNoAssignments) {
836 unsigned VN = VNI->id;
838 // If the VN has already been computed, just return it.
839 if (ThisValNoAssignments[VN] >= 0)
840 return ThisValNoAssignments[VN];
841 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
843 // If this val is not a copy from the other val, then it must be a new value
844 // number in the destination.
845 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
846 if (I == ThisFromOther.end()) {
847 NewVNInfo.push_back(VNI);
848 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
850 VNInfo *OtherValNo = I->second;
852 // Otherwise, this *is* a copy from the RHS. If the other side has already
853 // been computed, return it.
854 if (OtherValNoAssignments[OtherValNo->id] >= 0)
855 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
857 // Mark this value number as currently being computed, then ask what the
858 // ultimate value # of the other value is.
859 ThisValNoAssignments[VN] = -2;
860 unsigned UltimateVN =
861 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
862 OtherValNoAssignments, ThisValNoAssignments);
863 return ThisValNoAssignments[VN] = UltimateVN;
866 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
867 return std::find(V.begin(), V.end(), Val) != V.end();
870 /// SimpleJoin - Attempt to joint the specified interval into this one. The
871 /// caller of this method must guarantee that the RHS only contains a single
872 /// value number and that the RHS is not defined by a copy from this
873 /// interval. This returns false if the intervals are not joinable, or it
874 /// joins them and returns true.
875 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
876 assert(RHS.containsOneValue());
878 // Some number (potentially more than one) value numbers in the current
879 // interval may be defined as copies from the RHS. Scan the overlapping
880 // portions of the LHS and RHS, keeping track of this and looking for
881 // overlapping live ranges that are NOT defined as copies. If these exist, we
884 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
885 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
887 if (LHSIt->start < RHSIt->start) {
888 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
889 if (LHSIt != LHS.begin()) --LHSIt;
890 } else if (RHSIt->start < LHSIt->start) {
891 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
892 if (RHSIt != RHS.begin()) --RHSIt;
895 SmallVector<VNInfo*, 8> EliminatedLHSVals;
898 // Determine if these live intervals overlap.
899 bool Overlaps = false;
900 if (LHSIt->start <= RHSIt->start)
901 Overlaps = LHSIt->end > RHSIt->start;
903 Overlaps = RHSIt->end > LHSIt->start;
905 // If the live intervals overlap, there are two interesting cases: if the
906 // LHS interval is defined by a copy from the RHS, it's ok and we record
907 // that the LHS value # is the same as the RHS. If it's not, then we cannot
908 // coalesce these live ranges and we bail out.
910 // If we haven't already recorded that this value # is safe, check it.
911 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
912 // Copy from the RHS?
913 unsigned SrcReg = li_->getVNInfoSourceReg(LHSIt->valno);
914 if (SrcReg != RHS.reg)
915 return false; // Nope, bail out.
917 EliminatedLHSVals.push_back(LHSIt->valno);
920 // We know this entire LHS live range is okay, so skip it now.
921 if (++LHSIt == LHSEnd) break;
925 if (LHSIt->end < RHSIt->end) {
926 if (++LHSIt == LHSEnd) break;
928 // One interesting case to check here. It's possible that we have
929 // something like "X3 = Y" which defines a new value number in the LHS,
930 // and is the last use of this liverange of the RHS. In this case, we
931 // want to notice this copy (so that it gets coalesced away) even though
932 // the live ranges don't actually overlap.
933 if (LHSIt->start == RHSIt->end) {
934 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
935 // We already know that this value number is going to be merged in
936 // if coalescing succeeds. Just skip the liverange.
937 if (++LHSIt == LHSEnd) break;
939 // Otherwise, if this is a copy from the RHS, mark it as being merged
941 if (li_->getVNInfoSourceReg(LHSIt->valno) == RHS.reg) {
942 EliminatedLHSVals.push_back(LHSIt->valno);
944 // We know this entire LHS live range is okay, so skip it now.
945 if (++LHSIt == LHSEnd) break;
950 if (++RHSIt == RHSEnd) break;
954 // If we got here, we know that the coalescing will be successful and that
955 // the value numbers in EliminatedLHSVals will all be merged together. Since
956 // the most common case is that EliminatedLHSVals has a single number, we
957 // optimize for it: if there is more than one value, we merge them all into
958 // the lowest numbered one, then handle the interval as if we were merging
959 // with one value number.
961 if (EliminatedLHSVals.size() > 1) {
962 // Loop through all the equal value numbers merging them into the smallest
964 VNInfo *Smallest = EliminatedLHSVals[0];
965 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
966 if (EliminatedLHSVals[i]->id < Smallest->id) {
967 // Merge the current notion of the smallest into the smaller one.
968 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
969 Smallest = EliminatedLHSVals[i];
971 // Merge into the smallest.
972 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
977 assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
978 LHSValNo = EliminatedLHSVals[0];
981 // Okay, now that there is a single LHS value number that we're merging the
982 // RHS into, update the value number info for the LHS to indicate that the
983 // value number is defined where the RHS value number was.
984 const VNInfo *VNI = RHS.getValNumInfo(0);
985 LHSValNo->def = VNI->def;
986 LHSValNo->copy = VNI->copy;
988 // Okay, the final step is to loop over the RHS live intervals, adding them to
990 LHSValNo->hasPHIKill |= VNI->hasPHIKill;
991 LHS.addKills(LHSValNo, VNI->kills);
992 LHS.MergeRangesInAsValue(RHS, LHSValNo);
993 LHS.weight += RHS.weight;
994 if (RHS.preference && !LHS.preference)
995 LHS.preference = RHS.preference;
1000 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1001 /// returns false. Otherwise, if one of the intervals being joined is a
1002 /// physreg, this method always canonicalizes LHS to be it. The output
1003 /// "RHS" will not have been modified, so we can use this information
1004 /// below to update aliases.
1005 bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
1006 LiveInterval &RHS, bool &Swapped) {
1007 // Compute the final value assignment, assuming that the live ranges can be
1009 SmallVector<int, 16> LHSValNoAssignments;
1010 SmallVector<int, 16> RHSValNoAssignments;
1011 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1012 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1013 SmallVector<VNInfo*, 16> NewVNInfo;
1015 // If a live interval is a physical register, conservatively check if any
1016 // of its sub-registers is overlapping the live interval of the virtual
1017 // register. If so, do not coalesce.
1018 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1019 *tri_->getSubRegisters(LHS.reg)) {
1020 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
1021 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1022 DOUT << "Interfere with sub-register ";
1023 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1026 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1027 *tri_->getSubRegisters(RHS.reg)) {
1028 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
1029 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1030 DOUT << "Interfere with sub-register ";
1031 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1036 // Compute ultimate value numbers for the LHS and RHS values.
1037 if (RHS.containsOneValue()) {
1038 // Copies from a liveinterval with a single value are simple to handle and
1039 // very common, handle the special case here. This is important, because
1040 // often RHS is small and LHS is large (e.g. a physreg).
1042 // Find out if the RHS is defined as a copy from some value in the LHS.
1043 int RHSVal0DefinedFromLHS = -1;
1045 VNInfo *RHSValNoInfo = NULL;
1046 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
1047 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
1048 if ((RHSSrcReg == 0 || RHSSrcReg != LHS.reg)) {
1049 // If RHS is not defined as a copy from the LHS, we can use simpler and
1050 // faster checks to see if the live ranges are coalescable. This joiner
1051 // can't swap the LHS/RHS intervals though.
1052 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1053 return SimpleJoin(LHS, RHS);
1055 RHSValNoInfo = RHSValNoInfo0;
1058 // It was defined as a copy from the LHS, find out what value # it is.
1059 RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
1060 RHSValID = RHSValNoInfo->id;
1061 RHSVal0DefinedFromLHS = RHSValID;
1064 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1065 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1066 NewVNInfo.resize(LHS.getNumValNums(), NULL);
1068 // Okay, *all* of the values in LHS that are defined as a copy from RHS
1069 // should now get updated.
1070 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1073 unsigned VN = VNI->id;
1074 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1075 if (LHSSrcReg != RHS.reg) {
1076 // If this is not a copy from the RHS, its value number will be
1077 // unmodified by the coalescing.
1078 NewVNInfo[VN] = VNI;
1079 LHSValNoAssignments[VN] = VN;
1080 } else if (RHSValID == -1) {
1081 // Otherwise, it is a copy from the RHS, and we don't already have a
1082 // value# for it. Keep the current value number, but remember it.
1083 LHSValNoAssignments[VN] = RHSValID = VN;
1084 NewVNInfo[VN] = RHSValNoInfo;
1085 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1087 // Otherwise, use the specified value #.
1088 LHSValNoAssignments[VN] = RHSValID;
1089 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
1090 NewVNInfo[VN] = RHSValNoInfo;
1091 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1095 NewVNInfo[VN] = VNI;
1096 LHSValNoAssignments[VN] = VN;
1100 assert(RHSValID != -1 && "Didn't find value #?");
1101 RHSValNoAssignments[0] = RHSValID;
1102 if (RHSVal0DefinedFromLHS != -1) {
1103 // This path doesn't go through ComputeUltimateVN so just set
1105 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
1108 // Loop over the value numbers of the LHS, seeing if any are defined from
1110 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1113 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
1116 // DstReg is known to be a register in the LHS interval. If the src is
1117 // from the RHS interval, we can use its value #.
1118 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
1121 // Figure out the value # from the RHS.
1122 LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
1125 // Loop over the value numbers of the RHS, seeing if any are defined from
1127 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1130 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
1133 // DstReg is known to be a register in the RHS interval. If the src is
1134 // from the LHS interval, we can use its value #.
1135 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
1138 // Figure out the value # from the LHS.
1139 RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
1142 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1143 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1144 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1146 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1149 unsigned VN = VNI->id;
1150 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1152 ComputeUltimateVN(VNI, NewVNInfo,
1153 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1154 LHSValNoAssignments, RHSValNoAssignments);
1156 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1159 unsigned VN = VNI->id;
1160 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1162 // If this value number isn't a copy from the LHS, it's a new number.
1163 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1164 NewVNInfo.push_back(VNI);
1165 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1169 ComputeUltimateVN(VNI, NewVNInfo,
1170 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1171 RHSValNoAssignments, LHSValNoAssignments);
1175 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1176 // interval lists to see if these intervals are coalescable.
1177 LiveInterval::const_iterator I = LHS.begin();
1178 LiveInterval::const_iterator IE = LHS.end();
1179 LiveInterval::const_iterator J = RHS.begin();
1180 LiveInterval::const_iterator JE = RHS.end();
1182 // Skip ahead until the first place of potential sharing.
1183 if (I->start < J->start) {
1184 I = std::upper_bound(I, IE, J->start);
1185 if (I != LHS.begin()) --I;
1186 } else if (J->start < I->start) {
1187 J = std::upper_bound(J, JE, I->start);
1188 if (J != RHS.begin()) --J;
1192 // Determine if these two live ranges overlap.
1194 if (I->start < J->start) {
1195 Overlaps = I->end > J->start;
1197 Overlaps = J->end > I->start;
1200 // If so, check value # info to determine if they are really different.
1202 // If the live range overlap will map to the same value number in the
1203 // result liverange, we can still coalesce them. If not, we can't.
1204 if (LHSValNoAssignments[I->valno->id] !=
1205 RHSValNoAssignments[J->valno->id])
1209 if (I->end < J->end) {
1218 // Update kill info. Some live ranges are extended due to copy coalescing.
1219 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1220 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1221 VNInfo *VNI = I->first;
1222 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1223 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
1224 NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
1225 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
1228 // Update kill info. Some live ranges are extended due to copy coalescing.
1229 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1230 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1231 VNInfo *VNI = I->first;
1232 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1233 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
1234 NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
1235 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
1238 // If we get here, we know that we can coalesce the live ranges. Ask the
1239 // intervals to coalesce themselves now.
1240 if ((RHS.ranges.size() > LHS.ranges.size() &&
1241 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
1242 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1243 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
1246 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
1253 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1254 // depth of the basic block (the unsigned), and then on the MBB number.
1255 struct DepthMBBCompare {
1256 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1257 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1258 if (LHS.first > RHS.first) return true; // Deeper loops first
1259 return LHS.first == RHS.first &&
1260 LHS.second->getNumber() < RHS.second->getNumber();
1265 /// getRepIntervalSize - Returns the size of the interval that represents the
1266 /// specified register.
1268 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
1269 return Rc->getRepIntervalSize(Reg);
1272 /// CopyRecSort::operator - Join priority queue sorting function.
1274 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
1275 // Inner loops first.
1276 if (left.LoopDepth > right.LoopDepth)
1278 else if (left.LoopDepth == right.LoopDepth)
1279 if (left.isBackEdge && !right.isBackEdge)
1284 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1285 std::vector<CopyRec> &TryAgain) {
1286 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
1288 std::vector<CopyRec> VirtCopies;
1289 std::vector<CopyRec> PhysCopies;
1290 unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
1291 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1293 MachineInstr *Inst = MII++;
1295 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1296 unsigned SrcReg, DstReg;
1297 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1298 DstReg = Inst->getOperand(0).getReg();
1299 SrcReg = Inst->getOperand(1).getReg();
1300 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
1303 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1304 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1306 JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
1308 if (SrcIsPhys || DstIsPhys)
1309 PhysCopies.push_back(CopyRec(Inst, 0, false));
1311 VirtCopies.push_back(CopyRec(Inst, 0, false));
1318 // Try coalescing physical register + virtual register first.
1319 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1320 CopyRec &TheCopy = PhysCopies[i];
1322 if (!JoinCopy(TheCopy, Again))
1324 TryAgain.push_back(TheCopy);
1326 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1327 CopyRec &TheCopy = VirtCopies[i];
1329 if (!JoinCopy(TheCopy, Again))
1331 TryAgain.push_back(TheCopy);
1335 void SimpleRegisterCoalescing::joinIntervals() {
1336 DOUT << "********** JOINING INTERVALS ***********\n";
1339 JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
1341 std::vector<CopyRec> TryAgainList;
1342 if (loopInfo->begin() == loopInfo->end()) {
1343 // If there are no loops in the function, join intervals in function order.
1344 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1346 CopyCoalesceInMBB(I, TryAgainList);
1348 // Otherwise, join intervals in inner loops before other intervals.
1349 // Unfortunately we can't just iterate over loop hierarchy here because
1350 // there may be more MBB's than BB's. Collect MBB's for sorting.
1352 // Join intervals in the function prolog first. We want to join physical
1353 // registers with virtual registers before the intervals got too long.
1354 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1355 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1356 MachineBasicBlock *MBB = I;
1357 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1360 // Sort by loop depth.
1361 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1363 // Finally, join intervals in loop nest order.
1364 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1365 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1368 // Joining intervals can allow other intervals to be joined. Iteratively join
1369 // until we make no progress.
1371 SmallVector<CopyRec, 16> TryAgain;
1372 bool ProgressMade = true;
1373 while (ProgressMade) {
1374 ProgressMade = false;
1375 while (!JoinQueue->empty()) {
1376 CopyRec R = JoinQueue->pop();
1378 bool Success = JoinCopy(R, Again);
1380 ProgressMade = true;
1382 TryAgain.push_back(R);
1386 while (!TryAgain.empty()) {
1387 JoinQueue->push(TryAgain.back());
1388 TryAgain.pop_back();
1393 bool ProgressMade = true;
1394 while (ProgressMade) {
1395 ProgressMade = false;
1397 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1398 CopyRec &TheCopy = TryAgainList[i];
1401 bool Success = JoinCopy(TheCopy, Again);
1402 if (Success || !Again) {
1403 TheCopy.MI = 0; // Mark this one as done.
1404 ProgressMade = true;
1415 /// Return true if the two specified registers belong to different register
1416 /// classes. The registers may be either phys or virt regs.
1417 bool SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1418 unsigned RegB) const {
1420 // Get the register classes for the first reg.
1421 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1422 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1423 "Shouldn't consider two physregs!");
1424 return !mri_->getRegClass(RegB)->contains(RegA);
1427 // Compare against the regclass for the second reg.
1428 const TargetRegisterClass *RegClass = mri_->getRegClass(RegA);
1429 if (TargetRegisterInfo::isVirtualRegister(RegB))
1430 return RegClass != mri_->getRegClass(RegB);
1432 return !RegClass->contains(RegB);
1435 /// lastRegisterUse - Returns the last use of the specific register between
1436 /// cycles Start and End or NULL if there are no uses.
1438 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
1439 unsigned Reg, unsigned &UseIdx) const{
1441 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1442 MachineOperand *LastUse = NULL;
1443 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
1444 E = mri_->use_end(); I != E; ++I) {
1445 MachineOperand &Use = I.getOperand();
1446 MachineInstr *UseMI = Use.getParent();
1447 unsigned Idx = li_->getInstructionIndex(UseMI);
1448 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1456 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1459 // Skip deleted instructions
1460 MachineInstr *MI = li_->getInstructionFromIndex(e);
1461 while ((e - InstrSlots::NUM) >= s && !MI) {
1462 e -= InstrSlots::NUM;
1463 MI = li_->getInstructionFromIndex(e);
1465 if (e < s || MI == NULL)
1468 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1469 MachineOperand &Use = MI->getOperand(i);
1470 if (Use.isRegister() && Use.isUse() && Use.getReg() &&
1471 tri_->regsOverlap(Use.getReg(), Reg)) {
1477 e -= InstrSlots::NUM;
1484 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
1485 /// due to live range lengthening as the result of coalescing.
1486 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
1487 if (TargetRegisterInfo::isPhysicalRegister(reg))
1488 cerr << tri_->getName(reg);
1490 cerr << "%reg" << reg;
1493 void SimpleRegisterCoalescing::releaseMemory() {
1494 JoinedCopies.clear();
1497 static bool isZeroLengthInterval(LiveInterval *li) {
1498 for (LiveInterval::Ranges::const_iterator
1499 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
1500 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
1505 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1507 mri_ = &fn.getRegInfo();
1508 tm_ = &fn.getTarget();
1509 tri_ = tm_->getRegisterInfo();
1510 tii_ = tm_->getInstrInfo();
1511 li_ = &getAnalysis<LiveIntervals>();
1512 lv_ = &getAnalysis<LiveVariables>();
1513 loopInfo = &getAnalysis<MachineLoopInfo>();
1515 DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
1516 << "********** Function: "
1517 << ((Value*)mf_->getFunction())->getName() << '\n';
1519 allocatableRegs_ = tri_->getAllocatableSet(fn);
1520 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1521 E = tri_->regclass_end(); I != E; ++I)
1522 allocatableRCRegs_.insert(std::make_pair(*I,
1523 tri_->getAllocatableSet(fn, *I)));
1525 // Join (coalesce) intervals if requested.
1526 if (EnableJoining) {
1528 DOUT << "********** INTERVALS POST JOINING **********\n";
1529 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
1530 I->second.print(DOUT, tri_);
1534 // Delete all coalesced copies.
1535 for (SmallPtrSet<MachineInstr*,32>::iterator I = JoinedCopies.begin(),
1536 E = JoinedCopies.end(); I != E; ++I) {
1537 li_->RemoveMachineInstrFromMaps(*I);
1538 (*I)->eraseFromParent();
1543 // Perform a final pass over the instructions and compute spill weights
1544 // and remove identity moves.
1545 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1546 mbbi != mbbe; ++mbbi) {
1547 MachineBasicBlock* mbb = mbbi;
1548 unsigned loopDepth = loopInfo->getLoopDepth(mbb);
1550 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1552 // if the move will be an identity move delete it
1553 unsigned srcReg, dstReg;
1554 if (tii_->isMoveInstr(*mii, srcReg, dstReg) && srcReg == dstReg) {
1555 // remove from def list
1556 LiveInterval &RegInt = li_->getOrCreateInterval(srcReg);
1557 // If def of this move instruction is dead, remove its live range from
1558 // the dstination register's live interval.
1559 if (mii->registerDefIsDead(dstReg))
1560 ShortenDeadCopyLiveRange(RegInt, mii);
1561 li_->RemoveMachineInstrFromMaps(mii);
1562 mii = mbbi->erase(mii);
1565 SmallSet<unsigned, 4> UniqueUses;
1566 for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
1567 const MachineOperand &mop = mii->getOperand(i);
1568 if (mop.isRegister() && mop.getReg() &&
1569 TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
1570 unsigned reg = mop.getReg();
1571 // Multiple uses of reg by the same instruction. It should not
1572 // contribute to spill weight again.
1573 if (UniqueUses.count(reg) != 0)
1575 LiveInterval &RegInt = li_->getInterval(reg);
1577 li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
1578 UniqueUses.insert(reg);
1586 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1587 LiveInterval &LI = I->second;
1588 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1589 // If the live interval length is essentially zero, i.e. in every live
1590 // range the use follows def immediately, it doesn't make sense to spill
1591 // it and hope it will be easier to allocate for this li.
1592 if (isZeroLengthInterval(&LI))
1593 LI.weight = HUGE_VALF;
1595 bool isLoad = false;
1596 if (li_->isReMaterializable(LI, isLoad)) {
1597 // If all of the definitions of the interval are re-materializable,
1598 // it is a preferred candidate for spilling. If non of the defs are
1599 // loads, then it's potentially very cheap to re-materialize.
1600 // FIXME: this gets much more complicated once we support non-trivial
1601 // re-materialization.
1609 // Slightly prefer live interval that has been assigned a preferred reg.
1613 // Divide the weight of the interval by its size. This encourages
1614 // spilling of intervals that are large and have few uses, and
1615 // discourages spilling of small intervals with many uses.
1616 LI.weight /= LI.getSize();
1624 /// print - Implement the dump method.
1625 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
1629 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1630 return new SimpleRegisterCoalescing();
1633 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1634 DEFINING_FILE_FOR(SimpleRegisterCoalescing)