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 VNInfo *BValNo = BLR->valno;
102 // Get the location that B is defined at. Two options: either this value has
103 // an unknown definition point or it is defined at CopyIdx. If unknown, we
105 if (!BValNo->copy) return false;
106 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
108 // AValNo is the value number in A that defines the copy, A3 in the example.
109 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
110 VNInfo *AValNo = ALR->valno;
112 // If AValNo is defined as a copy from IntB, we can potentially process this.
113 // Get the instruction that defines this value number.
114 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
115 if (!SrcReg) return false; // Not defined by a copy.
117 // If the value number is not defined by a copy instruction, ignore it.
119 // If the source register comes from an interval other than IntB, we can't
121 if (SrcReg != IntB.reg) return false;
123 // Get the LiveRange in IntB that this value number starts with.
124 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
126 // Make sure that the end of the live range is inside the same block as
128 MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
130 ValLREndInst->getParent() != CopyMI->getParent()) return false;
132 // Okay, we now know that ValLR ends in the same block that the CopyMI
133 // live-range starts. If there are no intervening live ranges between them in
134 // IntB, we can merge them.
135 if (ValLR+1 != BLR) return false;
137 // If a live interval is a physical register, conservatively check if any
138 // of its sub-registers is overlapping the live interval of the virtual
139 // register. If so, do not coalesce.
140 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
141 *tri_->getSubRegisters(IntB.reg)) {
142 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
143 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
144 DOUT << "Interfere with sub-register ";
145 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
150 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
152 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
153 // We are about to delete CopyMI, so need to remove it as the 'instruction
154 // that defines this value #'. Update the the valnum with the new defining
156 BValNo->def = FillerStart;
159 // Okay, we can merge them. We need to insert a new liverange:
160 // [ValLR.end, BLR.begin) of either value number, then we merge the
161 // two value numbers.
162 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
164 // If the IntB live range is assigned to a physical register, and if that
165 // physreg has aliases,
166 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
167 // Update the liveintervals of sub-registers.
168 for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) {
169 LiveInterval &AliasLI = li_->getInterval(*AS);
170 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
171 AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
175 // Okay, merge "B1" into the same value number as "B0".
176 if (BValNo != ValLR->valno)
177 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
178 DOUT << " result = "; IntB.print(DOUT, tri_);
181 // If the source instruction was killing the source register before the
182 // merge, unset the isKill marker given the live range has been extended.
183 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
185 ValLREndInst->getOperand(UIdx).setIsKill(false);
191 /// HasOtherReachingDefs - Return true if there are definitions of IntB
192 /// other than BValNo val# that can reach uses of AValno val# of IntA.
193 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
197 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
199 if (AI->valno != AValNo) continue;
200 LiveInterval::Ranges::iterator BI =
201 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
202 if (BI != IntB.ranges.begin())
204 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
205 if (BI->valno == BValNo)
207 if (BI->start <= AI->start && BI->end > AI->start)
209 if (BI->start > AI->start && BI->start < AI->end)
216 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
217 /// being the source and IntB being the dest, thus this defines a value number
218 /// in IntB. If the source value number (in IntA) is defined by a commutable
219 /// instruction and its other operand is coalesced to the copy dest register,
220 /// see if we can transform the copy into a noop by commuting the definition. For
223 /// A3 = op A2 B0<kill>
225 /// B1 = A3 <- this copy
227 /// = op A3 <- more uses
231 /// B2 = op B0 A2<kill>
233 /// B1 = B2 <- now an identify copy
235 /// = op B2 <- more uses
237 /// This returns true if an interval was modified.
239 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
241 MachineInstr *CopyMI) {
242 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
244 // FIXME: For now, only eliminate the copy by commuting its def when the
245 // source register is a virtual register. We want to guard against cases
246 // where the copy is a back edge copy and commuting the def lengthen the
247 // live interval of the source register to the entire loop.
248 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
251 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
252 // the example above.
253 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
254 VNInfo *BValNo = BLR->valno;
256 // Get the location that B is defined at. Two options: either this value has
257 // an unknown definition point or it is defined at CopyIdx. If unknown, we
259 if (!BValNo->copy) return false;
260 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
262 // AValNo is the value number in A that defines the copy, A3 in the example.
263 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
264 VNInfo *AValNo = ALR->valno;
265 // If other defs can reach uses of this def, then it's not safe to perform
267 if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
269 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
270 const TargetInstrDesc &TID = DefMI->getDesc();
272 if (!TID.isCommutable() ||
273 !tii_->CommuteChangesDestination(DefMI, NewDstIdx))
276 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
277 unsigned NewReg = NewDstMO.getReg();
278 if (NewReg != IntB.reg || !NewDstMO.isKill())
281 // Make sure there are no other definitions of IntB that would reach the
282 // uses which the new definition can reach.
283 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
286 // At this point we have decided that it is legal to do this
287 // transformation. Start by commuting the instruction.
288 MachineBasicBlock *MBB = DefMI->getParent();
289 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
292 if (NewMI != DefMI) {
293 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
294 MBB->insert(DefMI, NewMI);
297 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
298 NewMI->getOperand(OpIdx).setIsKill();
300 bool BHasPHIKill = BValNo->hasPHIKill;
301 SmallVector<VNInfo*, 4> BDeadValNos;
302 SmallVector<unsigned, 4> BKills;
303 std::map<unsigned, unsigned> BExtend;
305 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
314 // then do not add kills of A to the newly created B interval.
315 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
317 BExtend[ALR->end] = BLR->end;
319 // Update uses of IntA of the specific Val# with IntB.
320 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
321 UE = mri_->use_end(); UI != UE;) {
322 MachineOperand &UseMO = UI.getOperand();
323 MachineInstr *UseMI = &*UI;
325 if (JoinedCopies.count(UseMI))
327 unsigned UseIdx = li_->getInstructionIndex(UseMI);
328 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
329 if (ULR->valno != AValNo)
331 UseMO.setReg(NewReg);
334 if (UseMO.isKill()) {
336 UseMO.setIsKill(false);
338 BKills.push_back(li_->getUseIndex(UseIdx)+1);
340 unsigned SrcReg, DstReg;
341 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg))
343 if (DstReg == IntB.reg) {
344 // This copy will become a noop. If it's defining a new val#,
345 // remove that val# as well. However this live range is being
346 // extended to the end of the existing live range defined by the copy.
347 unsigned DefIdx = li_->getDefIndex(UseIdx);
348 LiveInterval::iterator DLR = IntB.FindLiveRangeContaining(DefIdx);
349 BHasPHIKill |= DLR->valno->hasPHIKill;
350 assert(DLR->valno->def == DefIdx);
351 BDeadValNos.push_back(DLR->valno);
352 BExtend[DLR->start] = DLR->end;
353 JoinedCopies.insert(UseMI);
354 // If this is a kill but it's going to be removed, the last use
355 // of the same val# is the new kill.
361 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
362 // simply extend BLR if CopyMI doesn't end the range.
363 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
365 IntB.removeValNo(BValNo);
366 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
367 IntB.removeValNo(BDeadValNos[i]);
368 VNInfo *ValNo = IntB.getNextValue(ALR->start, 0, li_->getVNInfoAllocator());
369 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
371 if (AI->valno != AValNo) continue;
372 unsigned End = AI->end;
373 std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
374 if (EI != BExtend.end())
376 IntB.addRange(LiveRange(AI->start, End, ValNo));
378 IntB.addKills(ValNo, BKills);
379 ValNo->hasPHIKill = BHasPHIKill;
381 DOUT << " result = "; IntB.print(DOUT, tri_);
384 DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
385 IntA.removeValNo(AValNo);
386 DOUT << " result = "; IntA.print(DOUT, tri_);
393 /// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
395 bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
397 MachineBasicBlock *MBB = CopyMI->getParent();
398 const MachineLoop *L = loopInfo->getLoopFor(MBB);
401 if (MBB != L->getLoopLatch())
404 LiveInterval &LI = li_->getInterval(DstReg);
405 unsigned DefIdx = li_->getInstructionIndex(CopyMI);
406 LiveInterval::const_iterator DstLR =
407 LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
408 if (DstLR == LI.end())
410 unsigned KillIdx = li_->getInstructionIndex(&MBB->back()) + InstrSlots::NUM;
411 if (DstLR->valno->kills.size() == 1 &&
412 DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
417 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
418 /// update the subregister number if it is not zero. If DstReg is a
419 /// physical register and the existing subregister number of the def / use
420 /// being updated is not zero, make sure to set it to the correct physical
423 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
425 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
426 if (DstIsPhys && SubIdx) {
427 // Figure out the real physical register we are updating with.
428 DstReg = tri_->getSubReg(DstReg, SubIdx);
432 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
433 E = mri_->reg_end(); I != E; ) {
434 MachineOperand &O = I.getOperand();
437 unsigned UseSubIdx = O.getSubReg();
438 unsigned UseDstReg = DstReg;
440 UseDstReg = tri_->getSubReg(DstReg, UseSubIdx);
444 unsigned OldSubIdx = O.getSubReg();
445 // Sub-register indexes goes from small to large. e.g.
446 // RAX: 0 -> AL, 1 -> AH, 2 -> AX, 3 -> EAX
447 // EAX: 0 -> AL, 1 -> AH, 2 -> AX
448 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
449 // sub-register 2 is also AX.
450 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
451 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
459 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
460 /// due to live range lengthening as the result of coalescing.
461 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
463 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
464 UE = mri_->use_end(); UI != UE; ++UI) {
465 MachineOperand &UseMO = UI.getOperand();
466 if (UseMO.isKill()) {
467 MachineInstr *UseMI = UseMO.getParent();
469 if (!tii_->isMoveInstr(*UseMI, SReg, DReg))
471 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
472 if (JoinedCopies.count(UseMI))
474 LiveInterval::const_iterator UI = LI.FindLiveRangeContaining(UseIdx);
475 assert(UI != LI.end());
476 if (!LI.isKill(UI->valno, UseIdx+1))
477 UseMO.setIsKill(false);
482 /// ShortenDeadCopyLiveRange - Shorten a live range as it's artificially
483 /// extended by a dead copy. Mark the last use (if any) of the val# as kill
484 /// as ends the live range there. If there isn't another use, then this
485 /// live range is dead.
486 void SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
487 MachineInstr *CopyMI) {
488 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
489 LiveInterval::iterator MLR =
490 li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
491 unsigned RemoveStart = MLR->start;
492 unsigned RemoveEnd = MLR->end;
494 MachineOperand *LastUse = lastRegisterUse(RemoveStart, CopyIdx, li.reg,
497 // Shorten the liveinterval to the end of last use.
498 LastUse->setIsKill();
499 RemoveStart = li_->getDefIndex(LastUseIdx);
501 li.removeRange(RemoveStart, RemoveEnd, true);
503 li_->removeInterval(li.reg);
506 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
507 /// which are the src/dst of the copy instruction CopyMI. This returns true
508 /// if the copy was successfully coalesced away. If it is not currently
509 /// possible to coalesce this interval, but it may be possible if other
510 /// things get coalesced, then it returns true by reference in 'Again'.
511 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
512 MachineInstr *CopyMI = TheCopy.MI;
515 if (JoinedCopies.count(CopyMI))
516 return false; // Already done.
518 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
522 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
525 DstReg = CopyMI->getOperand(0).getReg();
526 SrcReg = CopyMI->getOperand(1).getReg();
527 } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
528 assert(0 && "Unrecognized copy instruction!");
532 // If they are already joined we continue.
533 if (SrcReg == DstReg) {
534 DOUT << "\tCopy already coalesced.\n";
535 return false; // Not coalescable.
538 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
539 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
541 // If they are both physical registers, we cannot join them.
542 if (SrcIsPhys && DstIsPhys) {
543 DOUT << "\tCan not coalesce physregs.\n";
544 return false; // Not coalescable.
547 // We only join virtual registers with allocatable physical registers.
548 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
549 DOUT << "\tSrc reg is unallocatable physreg.\n";
550 return false; // Not coalescable.
552 if (DstIsPhys && !allocatableRegs_[DstReg]) {
553 DOUT << "\tDst reg is unallocatable physreg.\n";
554 return false; // Not coalescable.
557 unsigned RealDstReg = 0;
559 SubIdx = CopyMI->getOperand(2).getImm();
561 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
562 // coalesced with AX.
563 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
565 } else if (DstIsPhys) {
566 // If this is a extract_subreg where dst is a physical register, e.g.
567 // cl = EXTRACT_SUBREG reg1024, 1
568 // then create and update the actual physical register allocated to RHS.
569 const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
570 for (const unsigned *SRs = tri_->getSuperRegisters(DstReg);
571 unsigned SR = *SRs; ++SRs) {
572 if (DstReg == tri_->getSubReg(SR, SubIdx) &&
578 assert(RealDstReg && "Invalid extra_subreg instruction!");
580 // For this type of EXTRACT_SUBREG, conservatively
581 // check if the live interval of the source register interfere with the
582 // actual super physical register we are trying to coalesce with.
583 LiveInterval &RHS = li_->getInterval(SrcReg);
584 if (li_->hasInterval(RealDstReg) &&
585 RHS.overlaps(li_->getInterval(RealDstReg))) {
586 DOUT << "Interfere with register ";
587 DEBUG(li_->getInterval(RealDstReg).print(DOUT, tri_));
588 return false; // Not coalescable
590 for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
591 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
592 DOUT << "Interfere with sub-register ";
593 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
594 return false; // Not coalescable
598 unsigned SrcSize= li_->getInterval(SrcReg).getSize() / InstrSlots::NUM;
599 unsigned DstSize= li_->getInterval(DstReg).getSize() / InstrSlots::NUM;
600 const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
601 unsigned Threshold = allocatableRCRegs_[RC].count();
602 // Be conservative. If both sides are virtual registers, do not coalesce
603 // if this will cause a high use density interval to target a smaller set
605 if (DstSize > Threshold || SrcSize > Threshold) {
606 LiveVariables::VarInfo &svi = lv_->getVarInfo(SrcReg);
607 LiveVariables::VarInfo &dvi = lv_->getVarInfo(DstReg);
608 if ((float)dvi.NumUses / DstSize < (float)svi.NumUses / SrcSize) {
609 Again = true; // May be possible to coalesce later.
614 } else if (differingRegisterClasses(SrcReg, DstReg)) {
615 // FIXME: What if the resul of a EXTRACT_SUBREG is then coalesced
616 // with another? If it's the resulting destination register, then
617 // the subidx must be propagated to uses (but only those defined
618 // by the EXTRACT_SUBREG). If it's being coalesced into another
619 // register, it should be safe because register is assumed to have
620 // the register class of the super-register.
622 // If they are not of the same register class, we cannot join them.
623 DOUT << "\tSrc/Dest are different register classes.\n";
624 // Allow the coalescer to try again in case either side gets coalesced to
625 // a physical register that's compatible with the other side. e.g.
626 // r1024 = MOV32to32_ r1025
627 // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
628 Again = true; // May be possible to coalesce later.
632 LiveInterval &SrcInt = li_->getInterval(SrcReg);
633 LiveInterval &DstInt = li_->getInterval(DstReg);
634 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
635 "Register mapping is horribly broken!");
637 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
638 DOUT << " and "; DstInt.print(DOUT, tri_);
641 // Check if it is necessary to propagate "isDead" property before intervals
643 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
644 bool isDead = mopd->isDead();
645 bool isShorten = false;
646 unsigned SrcStart = 0, RemoveStart = 0;
647 unsigned SrcEnd = 0, RemoveEnd = 0;
649 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
650 LiveInterval::iterator SrcLR =
651 SrcInt.FindLiveRangeContaining(li_->getUseIndex(CopyIdx));
652 RemoveStart = SrcStart = SrcLR->start;
653 RemoveEnd = SrcEnd = SrcLR->end;
654 if (SrcEnd > li_->getDefIndex(CopyIdx)) {
655 // If there are other uses of SrcReg beyond the copy, there is nothing to do.
659 MachineOperand *LastUse =
660 lastRegisterUse(SrcStart, CopyIdx, SrcReg, LastUseIdx);
662 // There are uses before the copy, just shorten the live range to the end
664 LastUse->setIsKill();
667 RemoveStart = li_->getDefIndex(LastUseIdx);
669 // This live range is truly dead. Remove it.
670 MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
671 if (SrcMI && SrcMI->modifiesRegister(SrcReg, tri_))
672 // A dead def should have a single cycle interval.
678 // We need to be careful about coalescing a source physical register with a
679 // virtual register. Once the coalescing is done, it cannot be broken and
680 // these are not spillable! If the destination interval uses are far away,
681 // think twice about coalescing them!
682 if (!mopd->isDead() && (SrcIsPhys || DstIsPhys) && !isExtSubReg) {
683 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
684 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
685 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
686 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
687 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
688 if (TheCopy.isBackEdge)
689 Threshold *= 2; // Favors back edge copies.
691 // If the virtual register live interval is long but it has low use desity,
692 // do not join them, instead mark the physical register as its allocation
694 unsigned Length = JoinVInt.getSize() / InstrSlots::NUM;
695 LiveVariables::VarInfo &vi = lv_->getVarInfo(JoinVReg);
696 if (Length > Threshold &&
697 (((float)vi.NumUses / Length) < (1.0 / Threshold))) {
698 JoinVInt.preference = JoinPReg;
700 DOUT << "\tMay tie down a physical register, abort!\n";
701 Again = true; // May be possible to coalesce later.
706 // Okay, attempt to join these two intervals. On failure, this returns false.
707 // Otherwise, if one of the intervals being joined is a physreg, this method
708 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
709 // been modified, so we can use this information below to update aliases.
710 bool Swapped = false;
711 if (JoinIntervals(DstInt, SrcInt, Swapped)) {
713 // Result of the copy is dead. Propagate this property.
715 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
716 "Live-in must be a physical register!");
717 // Live-in to the function but dead. Remove it from entry live-in set.
718 // JoinIntervals may end up swapping the two intervals.
719 mf_->begin()->removeLiveIn(SrcReg);
721 MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
723 int DeadIdx = SrcMI->findRegisterDefOperandIdx(SrcReg, false, tri_);
725 SrcMI->getOperand(DeadIdx).setIsDead();
730 if (isShorten || isDead) {
731 // Shorten the destination live interval.
733 SrcInt.removeRange(RemoveStart, RemoveEnd, true);
736 // Coalescing failed.
738 // If we can eliminate the copy without merging the live ranges, do so now.
740 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
741 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
742 JoinedCopies.insert(CopyMI);
746 // Otherwise, we are unable to join the intervals.
747 DOUT << "Interference!\n";
748 Again = true; // May be possible to coalesce later.
752 LiveInterval *ResSrcInt = &SrcInt;
753 LiveInterval *ResDstInt = &DstInt;
755 std::swap(SrcReg, DstReg);
756 std::swap(ResSrcInt, ResDstInt);
758 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
759 "LiveInterval::join didn't work right!");
761 // If we're about to merge live ranges into a physical register live range,
762 // we have to update any aliased register's live ranges to indicate that they
763 // have clobbered values for this range.
764 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
765 // If this is a extract_subreg where dst is a physical register, e.g.
766 // cl = EXTRACT_SUBREG reg1024, 1
767 // then create and update the actual physical register allocated to RHS.
769 LiveInterval &RealDstInt = li_->getOrCreateInterval(RealDstReg);
770 SmallSet<const VNInfo*, 4> CopiedValNos;
771 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
772 E = ResSrcInt->ranges.end(); I != E; ++I) {
773 LiveInterval::const_iterator DstLR =
774 ResDstInt->FindLiveRangeContaining(I->start);
775 assert(DstLR != ResDstInt->end() && "Invalid joined interval!");
776 const VNInfo *DstValNo = DstLR->valno;
777 if (CopiedValNos.insert(DstValNo)) {
778 VNInfo *ValNo = RealDstInt.getNextValue(DstValNo->def, DstValNo->copy,
779 li_->getVNInfoAllocator());
780 ValNo->hasPHIKill = DstValNo->hasPHIKill;
781 RealDstInt.addKills(ValNo, DstValNo->kills);
782 RealDstInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
788 // Update the liveintervals of sub-registers.
789 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
790 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
791 li_->getVNInfoAllocator());
793 // Merge use info if the destination is a virtual register.
794 LiveVariables::VarInfo& dVI = lv_->getVarInfo(DstReg);
795 LiveVariables::VarInfo& sVI = lv_->getVarInfo(SrcReg);
796 dVI.NumUses += sVI.NumUses;
799 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
800 // larger super-register.
801 if (isExtSubReg && !SrcIsPhys && !DstIsPhys) {
803 ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
804 std::swap(SrcReg, DstReg);
805 std::swap(ResSrcInt, ResDstInt);
810 // Add all copies that define val# in the source interval into the queue.
811 for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
812 e = ResSrcInt->vni_end(); i != e; ++i) {
813 const VNInfo *vni = *i;
814 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
816 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
817 unsigned NewSrcReg, NewDstReg;
819 JoinedCopies.count(CopyMI) == 0 &&
820 tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg)) {
821 unsigned LoopDepth = loopInfo->getLoopDepth(CopyMI->getParent());
822 JoinQueue->push(CopyRec(CopyMI, LoopDepth,
823 isBackEdgeCopy(CopyMI, DstReg)));
828 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, tri_);
831 // Remember to delete the copy instruction.
832 JoinedCopies.insert(CopyMI);
834 // Some live range has been lengthened due to colaescing, eliminate the
835 // unnecessary kills.
836 RemoveUnnecessaryKills(SrcReg, *ResDstInt);
837 if (TargetRegisterInfo::isVirtualRegister(DstReg))
838 RemoveUnnecessaryKills(DstReg, *ResDstInt);
840 // SrcReg is guarateed to be the register whose live interval that is
842 li_->removeInterval(SrcReg);
843 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
849 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
850 /// compute what the resultant value numbers for each value in the input two
851 /// ranges will be. This is complicated by copies between the two which can
852 /// and will commonly cause multiple value numbers to be merged into one.
854 /// VN is the value number that we're trying to resolve. InstDefiningValue
855 /// keeps track of the new InstDefiningValue assignment for the result
856 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
857 /// whether a value in this or other is a copy from the opposite set.
858 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
859 /// already been assigned.
861 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
862 /// contains the value number the copy is from.
864 static unsigned ComputeUltimateVN(VNInfo *VNI,
865 SmallVector<VNInfo*, 16> &NewVNInfo,
866 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
867 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
868 SmallVector<int, 16> &ThisValNoAssignments,
869 SmallVector<int, 16> &OtherValNoAssignments) {
870 unsigned VN = VNI->id;
872 // If the VN has already been computed, just return it.
873 if (ThisValNoAssignments[VN] >= 0)
874 return ThisValNoAssignments[VN];
875 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
877 // If this val is not a copy from the other val, then it must be a new value
878 // number in the destination.
879 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
880 if (I == ThisFromOther.end()) {
881 NewVNInfo.push_back(VNI);
882 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
884 VNInfo *OtherValNo = I->second;
886 // Otherwise, this *is* a copy from the RHS. If the other side has already
887 // been computed, return it.
888 if (OtherValNoAssignments[OtherValNo->id] >= 0)
889 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
891 // Mark this value number as currently being computed, then ask what the
892 // ultimate value # of the other value is.
893 ThisValNoAssignments[VN] = -2;
894 unsigned UltimateVN =
895 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
896 OtherValNoAssignments, ThisValNoAssignments);
897 return ThisValNoAssignments[VN] = UltimateVN;
900 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
901 return std::find(V.begin(), V.end(), Val) != V.end();
904 /// SimpleJoin - Attempt to joint the specified interval into this one. The
905 /// caller of this method must guarantee that the RHS only contains a single
906 /// value number and that the RHS is not defined by a copy from this
907 /// interval. This returns false if the intervals are not joinable, or it
908 /// joins them and returns true.
909 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
910 assert(RHS.containsOneValue());
912 // Some number (potentially more than one) value numbers in the current
913 // interval may be defined as copies from the RHS. Scan the overlapping
914 // portions of the LHS and RHS, keeping track of this and looking for
915 // overlapping live ranges that are NOT defined as copies. If these exist, we
918 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
919 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
921 if (LHSIt->start < RHSIt->start) {
922 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
923 if (LHSIt != LHS.begin()) --LHSIt;
924 } else if (RHSIt->start < LHSIt->start) {
925 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
926 if (RHSIt != RHS.begin()) --RHSIt;
929 SmallVector<VNInfo*, 8> EliminatedLHSVals;
932 // Determine if these live intervals overlap.
933 bool Overlaps = false;
934 if (LHSIt->start <= RHSIt->start)
935 Overlaps = LHSIt->end > RHSIt->start;
937 Overlaps = RHSIt->end > LHSIt->start;
939 // If the live intervals overlap, there are two interesting cases: if the
940 // LHS interval is defined by a copy from the RHS, it's ok and we record
941 // that the LHS value # is the same as the RHS. If it's not, then we cannot
942 // coalesce these live ranges and we bail out.
944 // If we haven't already recorded that this value # is safe, check it.
945 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
946 // Copy from the RHS?
947 unsigned SrcReg = li_->getVNInfoSourceReg(LHSIt->valno);
948 if (SrcReg != RHS.reg)
949 return false; // Nope, bail out.
951 EliminatedLHSVals.push_back(LHSIt->valno);
954 // We know this entire LHS live range is okay, so skip it now.
955 if (++LHSIt == LHSEnd) break;
959 if (LHSIt->end < RHSIt->end) {
960 if (++LHSIt == LHSEnd) break;
962 // One interesting case to check here. It's possible that we have
963 // something like "X3 = Y" which defines a new value number in the LHS,
964 // and is the last use of this liverange of the RHS. In this case, we
965 // want to notice this copy (so that it gets coalesced away) even though
966 // the live ranges don't actually overlap.
967 if (LHSIt->start == RHSIt->end) {
968 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
969 // We already know that this value number is going to be merged in
970 // if coalescing succeeds. Just skip the liverange.
971 if (++LHSIt == LHSEnd) break;
973 // Otherwise, if this is a copy from the RHS, mark it as being merged
975 if (li_->getVNInfoSourceReg(LHSIt->valno) == RHS.reg) {
976 EliminatedLHSVals.push_back(LHSIt->valno);
978 // We know this entire LHS live range is okay, so skip it now.
979 if (++LHSIt == LHSEnd) break;
984 if (++RHSIt == RHSEnd) break;
988 // If we got here, we know that the coalescing will be successful and that
989 // the value numbers in EliminatedLHSVals will all be merged together. Since
990 // the most common case is that EliminatedLHSVals has a single number, we
991 // optimize for it: if there is more than one value, we merge them all into
992 // the lowest numbered one, then handle the interval as if we were merging
993 // with one value number.
995 if (EliminatedLHSVals.size() > 1) {
996 // Loop through all the equal value numbers merging them into the smallest
998 VNInfo *Smallest = EliminatedLHSVals[0];
999 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1000 if (EliminatedLHSVals[i]->id < Smallest->id) {
1001 // Merge the current notion of the smallest into the smaller one.
1002 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1003 Smallest = EliminatedLHSVals[i];
1005 // Merge into the smallest.
1006 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1009 LHSValNo = Smallest;
1011 assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
1012 LHSValNo = EliminatedLHSVals[0];
1015 // Okay, now that there is a single LHS value number that we're merging the
1016 // RHS into, update the value number info for the LHS to indicate that the
1017 // value number is defined where the RHS value number was.
1018 const VNInfo *VNI = RHS.getValNumInfo(0);
1019 LHSValNo->def = VNI->def;
1020 LHSValNo->copy = VNI->copy;
1022 // Okay, the final step is to loop over the RHS live intervals, adding them to
1024 LHSValNo->hasPHIKill |= VNI->hasPHIKill;
1025 LHS.addKills(LHSValNo, VNI->kills);
1026 LHS.MergeRangesInAsValue(RHS, LHSValNo);
1027 LHS.weight += RHS.weight;
1028 if (RHS.preference && !LHS.preference)
1029 LHS.preference = RHS.preference;
1034 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1035 /// returns false. Otherwise, if one of the intervals being joined is a
1036 /// physreg, this method always canonicalizes LHS to be it. The output
1037 /// "RHS" will not have been modified, so we can use this information
1038 /// below to update aliases.
1039 bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
1040 LiveInterval &RHS, bool &Swapped) {
1041 // Compute the final value assignment, assuming that the live ranges can be
1043 SmallVector<int, 16> LHSValNoAssignments;
1044 SmallVector<int, 16> RHSValNoAssignments;
1045 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1046 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1047 SmallVector<VNInfo*, 16> NewVNInfo;
1049 // If a live interval is a physical register, conservatively check if any
1050 // of its sub-registers is overlapping the live interval of the virtual
1051 // register. If so, do not coalesce.
1052 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1053 *tri_->getSubRegisters(LHS.reg)) {
1054 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
1055 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1056 DOUT << "Interfere with sub-register ";
1057 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1060 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1061 *tri_->getSubRegisters(RHS.reg)) {
1062 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
1063 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1064 DOUT << "Interfere with sub-register ";
1065 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1070 // Compute ultimate value numbers for the LHS and RHS values.
1071 if (RHS.containsOneValue()) {
1072 // Copies from a liveinterval with a single value are simple to handle and
1073 // very common, handle the special case here. This is important, because
1074 // often RHS is small and LHS is large (e.g. a physreg).
1076 // Find out if the RHS is defined as a copy from some value in the LHS.
1077 int RHSVal0DefinedFromLHS = -1;
1079 VNInfo *RHSValNoInfo = NULL;
1080 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
1081 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
1082 if ((RHSSrcReg == 0 || RHSSrcReg != LHS.reg)) {
1083 // If RHS is not defined as a copy from the LHS, we can use simpler and
1084 // faster checks to see if the live ranges are coalescable. This joiner
1085 // can't swap the LHS/RHS intervals though.
1086 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1087 return SimpleJoin(LHS, RHS);
1089 RHSValNoInfo = RHSValNoInfo0;
1092 // It was defined as a copy from the LHS, find out what value # it is.
1093 RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
1094 RHSValID = RHSValNoInfo->id;
1095 RHSVal0DefinedFromLHS = RHSValID;
1098 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1099 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1100 NewVNInfo.resize(LHS.getNumValNums(), NULL);
1102 // Okay, *all* of the values in LHS that are defined as a copy from RHS
1103 // should now get updated.
1104 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1107 unsigned VN = VNI->id;
1108 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1109 if (LHSSrcReg != RHS.reg) {
1110 // If this is not a copy from the RHS, its value number will be
1111 // unmodified by the coalescing.
1112 NewVNInfo[VN] = VNI;
1113 LHSValNoAssignments[VN] = VN;
1114 } else if (RHSValID == -1) {
1115 // Otherwise, it is a copy from the RHS, and we don't already have a
1116 // value# for it. Keep the current value number, but remember it.
1117 LHSValNoAssignments[VN] = RHSValID = VN;
1118 NewVNInfo[VN] = RHSValNoInfo;
1119 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1121 // Otherwise, use the specified value #.
1122 LHSValNoAssignments[VN] = RHSValID;
1123 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
1124 NewVNInfo[VN] = RHSValNoInfo;
1125 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1129 NewVNInfo[VN] = VNI;
1130 LHSValNoAssignments[VN] = VN;
1134 assert(RHSValID != -1 && "Didn't find value #?");
1135 RHSValNoAssignments[0] = RHSValID;
1136 if (RHSVal0DefinedFromLHS != -1) {
1137 // This path doesn't go through ComputeUltimateVN so just set
1139 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
1142 // Loop over the value numbers of the LHS, seeing if any are defined from
1144 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1147 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
1150 // DstReg is known to be a register in the LHS interval. If the src is
1151 // from the RHS interval, we can use its value #.
1152 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
1155 // Figure out the value # from the RHS.
1156 LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
1159 // Loop over the value numbers of the RHS, seeing if any are defined from
1161 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1164 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
1167 // DstReg is known to be a register in the RHS interval. If the src is
1168 // from the LHS interval, we can use its value #.
1169 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
1172 // Figure out the value # from the LHS.
1173 RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
1176 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1177 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1178 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1180 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1183 unsigned VN = VNI->id;
1184 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1186 ComputeUltimateVN(VNI, NewVNInfo,
1187 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1188 LHSValNoAssignments, RHSValNoAssignments);
1190 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1193 unsigned VN = VNI->id;
1194 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1196 // If this value number isn't a copy from the LHS, it's a new number.
1197 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1198 NewVNInfo.push_back(VNI);
1199 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1203 ComputeUltimateVN(VNI, NewVNInfo,
1204 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1205 RHSValNoAssignments, LHSValNoAssignments);
1209 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1210 // interval lists to see if these intervals are coalescable.
1211 LiveInterval::const_iterator I = LHS.begin();
1212 LiveInterval::const_iterator IE = LHS.end();
1213 LiveInterval::const_iterator J = RHS.begin();
1214 LiveInterval::const_iterator JE = RHS.end();
1216 // Skip ahead until the first place of potential sharing.
1217 if (I->start < J->start) {
1218 I = std::upper_bound(I, IE, J->start);
1219 if (I != LHS.begin()) --I;
1220 } else if (J->start < I->start) {
1221 J = std::upper_bound(J, JE, I->start);
1222 if (J != RHS.begin()) --J;
1226 // Determine if these two live ranges overlap.
1228 if (I->start < J->start) {
1229 Overlaps = I->end > J->start;
1231 Overlaps = J->end > I->start;
1234 // If so, check value # info to determine if they are really different.
1236 // If the live range overlap will map to the same value number in the
1237 // result liverange, we can still coalesce them. If not, we can't.
1238 if (LHSValNoAssignments[I->valno->id] !=
1239 RHSValNoAssignments[J->valno->id])
1243 if (I->end < J->end) {
1252 // Update kill info. Some live ranges are extended due to copy coalescing.
1253 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1254 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1255 VNInfo *VNI = I->first;
1256 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1257 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
1258 NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
1259 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
1262 // Update kill info. Some live ranges are extended due to copy coalescing.
1263 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1264 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1265 VNInfo *VNI = I->first;
1266 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1267 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
1268 NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
1269 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
1272 // If we get here, we know that we can coalesce the live ranges. Ask the
1273 // intervals to coalesce themselves now.
1274 if ((RHS.ranges.size() > LHS.ranges.size() &&
1275 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
1276 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1277 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
1280 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
1287 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1288 // depth of the basic block (the unsigned), and then on the MBB number.
1289 struct DepthMBBCompare {
1290 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1291 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1292 if (LHS.first > RHS.first) return true; // Deeper loops first
1293 return LHS.first == RHS.first &&
1294 LHS.second->getNumber() < RHS.second->getNumber();
1299 /// getRepIntervalSize - Returns the size of the interval that represents the
1300 /// specified register.
1302 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
1303 return Rc->getRepIntervalSize(Reg);
1306 /// CopyRecSort::operator - Join priority queue sorting function.
1308 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
1309 // Inner loops first.
1310 if (left.LoopDepth > right.LoopDepth)
1312 else if (left.LoopDepth == right.LoopDepth)
1313 if (left.isBackEdge && !right.isBackEdge)
1318 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1319 std::vector<CopyRec> &TryAgain) {
1320 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
1322 std::vector<CopyRec> VirtCopies;
1323 std::vector<CopyRec> PhysCopies;
1324 unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
1325 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1327 MachineInstr *Inst = MII++;
1329 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1330 unsigned SrcReg, DstReg;
1331 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1332 DstReg = Inst->getOperand(0).getReg();
1333 SrcReg = Inst->getOperand(1).getReg();
1334 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
1337 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1338 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1340 JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
1342 if (SrcIsPhys || DstIsPhys)
1343 PhysCopies.push_back(CopyRec(Inst, 0, false));
1345 VirtCopies.push_back(CopyRec(Inst, 0, false));
1352 // Try coalescing physical register + virtual register first.
1353 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1354 CopyRec &TheCopy = PhysCopies[i];
1356 if (!JoinCopy(TheCopy, Again))
1358 TryAgain.push_back(TheCopy);
1360 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1361 CopyRec &TheCopy = VirtCopies[i];
1363 if (!JoinCopy(TheCopy, Again))
1365 TryAgain.push_back(TheCopy);
1369 void SimpleRegisterCoalescing::joinIntervals() {
1370 DOUT << "********** JOINING INTERVALS ***********\n";
1373 JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
1375 std::vector<CopyRec> TryAgainList;
1376 if (loopInfo->begin() == loopInfo->end()) {
1377 // If there are no loops in the function, join intervals in function order.
1378 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1380 CopyCoalesceInMBB(I, TryAgainList);
1382 // Otherwise, join intervals in inner loops before other intervals.
1383 // Unfortunately we can't just iterate over loop hierarchy here because
1384 // there may be more MBB's than BB's. Collect MBB's for sorting.
1386 // Join intervals in the function prolog first. We want to join physical
1387 // registers with virtual registers before the intervals got too long.
1388 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1389 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1390 MachineBasicBlock *MBB = I;
1391 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1394 // Sort by loop depth.
1395 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1397 // Finally, join intervals in loop nest order.
1398 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1399 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1402 // Joining intervals can allow other intervals to be joined. Iteratively join
1403 // until we make no progress.
1405 SmallVector<CopyRec, 16> TryAgain;
1406 bool ProgressMade = true;
1407 while (ProgressMade) {
1408 ProgressMade = false;
1409 while (!JoinQueue->empty()) {
1410 CopyRec R = JoinQueue->pop();
1412 bool Success = JoinCopy(R, Again);
1414 ProgressMade = true;
1416 TryAgain.push_back(R);
1420 while (!TryAgain.empty()) {
1421 JoinQueue->push(TryAgain.back());
1422 TryAgain.pop_back();
1427 bool ProgressMade = true;
1428 while (ProgressMade) {
1429 ProgressMade = false;
1431 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1432 CopyRec &TheCopy = TryAgainList[i];
1435 bool Success = JoinCopy(TheCopy, Again);
1436 if (Success || !Again) {
1437 TheCopy.MI = 0; // Mark this one as done.
1438 ProgressMade = true;
1449 /// Return true if the two specified registers belong to different register
1450 /// classes. The registers may be either phys or virt regs.
1451 bool SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1452 unsigned RegB) const {
1454 // Get the register classes for the first reg.
1455 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1456 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1457 "Shouldn't consider two physregs!");
1458 return !mri_->getRegClass(RegB)->contains(RegA);
1461 // Compare against the regclass for the second reg.
1462 const TargetRegisterClass *RegClass = mri_->getRegClass(RegA);
1463 if (TargetRegisterInfo::isVirtualRegister(RegB))
1464 return RegClass != mri_->getRegClass(RegB);
1466 return !RegClass->contains(RegB);
1469 /// lastRegisterUse - Returns the last use of the specific register between
1470 /// cycles Start and End or NULL if there are no uses.
1472 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
1473 unsigned Reg, unsigned &UseIdx) const{
1475 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1476 MachineOperand *LastUse = NULL;
1477 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
1478 E = mri_->use_end(); I != E; ++I) {
1479 MachineOperand &Use = I.getOperand();
1480 MachineInstr *UseMI = Use.getParent();
1481 unsigned Idx = li_->getInstructionIndex(UseMI);
1482 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1490 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1493 // Skip deleted instructions
1494 MachineInstr *MI = li_->getInstructionFromIndex(e);
1495 while ((e - InstrSlots::NUM) >= s && !MI) {
1496 e -= InstrSlots::NUM;
1497 MI = li_->getInstructionFromIndex(e);
1499 if (e < s || MI == NULL)
1502 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1503 MachineOperand &Use = MI->getOperand(i);
1504 if (Use.isRegister() && Use.isUse() && Use.getReg() &&
1505 tri_->regsOverlap(Use.getReg(), Reg)) {
1511 e -= InstrSlots::NUM;
1518 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
1519 if (TargetRegisterInfo::isPhysicalRegister(reg))
1520 cerr << tri_->getName(reg);
1522 cerr << "%reg" << reg;
1525 void SimpleRegisterCoalescing::releaseMemory() {
1526 JoinedCopies.clear();
1529 static bool isZeroLengthInterval(LiveInterval *li) {
1530 for (LiveInterval::Ranges::const_iterator
1531 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
1532 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
1537 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1539 mri_ = &fn.getRegInfo();
1540 tm_ = &fn.getTarget();
1541 tri_ = tm_->getRegisterInfo();
1542 tii_ = tm_->getInstrInfo();
1543 li_ = &getAnalysis<LiveIntervals>();
1544 lv_ = &getAnalysis<LiveVariables>();
1545 loopInfo = &getAnalysis<MachineLoopInfo>();
1547 DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
1548 << "********** Function: "
1549 << ((Value*)mf_->getFunction())->getName() << '\n';
1551 allocatableRegs_ = tri_->getAllocatableSet(fn);
1552 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1553 E = tri_->regclass_end(); I != E; ++I)
1554 allocatableRCRegs_.insert(std::make_pair(*I,
1555 tri_->getAllocatableSet(fn, *I)));
1557 // Join (coalesce) intervals if requested.
1558 if (EnableJoining) {
1560 DOUT << "********** INTERVALS POST JOINING **********\n";
1561 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
1562 I->second.print(DOUT, tri_);
1566 // Delete all coalesced copies.
1567 for (SmallPtrSet<MachineInstr*,32>::iterator I = JoinedCopies.begin(),
1568 E = JoinedCopies.end(); I != E; ++I) {
1569 li_->RemoveMachineInstrFromMaps(*I);
1570 (*I)->eraseFromParent();
1575 // Perform a final pass over the instructions and compute spill weights
1576 // and remove identity moves.
1577 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1578 mbbi != mbbe; ++mbbi) {
1579 MachineBasicBlock* mbb = mbbi;
1580 unsigned loopDepth = loopInfo->getLoopDepth(mbb);
1582 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1584 // if the move will be an identity move delete it
1585 unsigned srcReg, dstReg;
1586 if (tii_->isMoveInstr(*mii, srcReg, dstReg) && srcReg == dstReg) {
1587 // remove from def list
1588 LiveInterval &RegInt = li_->getOrCreateInterval(srcReg);
1589 // If def of this move instruction is dead, remove its live range from
1590 // the dstination register's live interval.
1591 if (mii->registerDefIsDead(dstReg))
1592 ShortenDeadCopyLiveRange(RegInt, mii);
1593 li_->RemoveMachineInstrFromMaps(mii);
1594 mii = mbbi->erase(mii);
1597 SmallSet<unsigned, 4> UniqueUses;
1598 for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
1599 const MachineOperand &mop = mii->getOperand(i);
1600 if (mop.isRegister() && mop.getReg() &&
1601 TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
1602 unsigned reg = mop.getReg();
1603 // Multiple uses of reg by the same instruction. It should not
1604 // contribute to spill weight again.
1605 if (UniqueUses.count(reg) != 0)
1607 LiveInterval &RegInt = li_->getInterval(reg);
1609 li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
1610 UniqueUses.insert(reg);
1618 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1619 LiveInterval &LI = I->second;
1620 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
1621 // If the live interval length is essentially zero, i.e. in every live
1622 // range the use follows def immediately, it doesn't make sense to spill
1623 // it and hope it will be easier to allocate for this li.
1624 if (isZeroLengthInterval(&LI))
1625 LI.weight = HUGE_VALF;
1627 bool isLoad = false;
1628 if (li_->isReMaterializable(LI, isLoad)) {
1629 // If all of the definitions of the interval are re-materializable,
1630 // it is a preferred candidate for spilling. If non of the defs are
1631 // loads, then it's potentially very cheap to re-materialize.
1632 // FIXME: this gets much more complicated once we support non-trivial
1633 // re-materialization.
1641 // Slightly prefer live interval that has been assigned a preferred reg.
1645 // Divide the weight of the interval by its size. This encourages
1646 // spilling of intervals that are large and have few uses, and
1647 // discourages spilling of small intervals with many uses.
1648 LI.weight /= LI.getSize();
1656 /// print - Implement the dump method.
1657 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
1661 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1662 return new SimpleRegisterCoalescing();
1665 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1666 DEFINING_FILE_FOR(SimpleRegisterCoalescing)