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/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/RegisterCoalescer.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetOptions.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(numSubJoins , "Number of subclass joins performed");
40 STATISTIC(numCommutes , "Number of instruction commuting performed");
41 STATISTIC(numExtends , "Number of copies extended");
42 STATISTIC(NumReMats , "Number of instructions re-materialized");
43 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
44 STATISTIC(numAborts , "Number of times interval joining aborted");
46 char SimpleRegisterCoalescing::ID = 0;
48 EnableJoining("join-liveintervals",
49 cl::desc("Coalesce copies (default=true)"),
53 NewHeuristic("new-coalescer-heuristic",
54 cl::desc("Use new coalescer heuristic"),
55 cl::init(false), cl::Hidden);
58 CrossClassJoin("join-subclass-copies",
59 cl::desc("Coalesce copies to sub- register class"),
60 cl::init(false), cl::Hidden);
62 static RegisterPass<SimpleRegisterCoalescing>
63 X("simple-register-coalescing", "Simple Register Coalescing");
65 // Declare that we implement the RegisterCoalescer interface
66 static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
68 const PassInfo *const llvm::SimpleRegisterCoalescingID = &X;
70 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
71 AU.addRequired<LiveIntervals>();
72 AU.addPreserved<LiveIntervals>();
73 AU.addRequired<MachineLoopInfo>();
74 AU.addPreserved<MachineLoopInfo>();
75 AU.addPreservedID(MachineDominatorsID);
77 AU.addPreservedID(StrongPHIEliminationID);
79 AU.addPreservedID(PHIEliminationID);
80 AU.addPreservedID(TwoAddressInstructionPassID);
81 MachineFunctionPass::getAnalysisUsage(AU);
84 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
85 /// being the source and IntB being the dest, thus this defines a value number
86 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
87 /// see if we can merge these two pieces of B into a single value number,
88 /// eliminating a copy. For example:
92 /// B1 = A3 <- this copy
94 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
95 /// value number to be replaced with B0 (which simplifies the B liveinterval).
97 /// This returns true if an interval was modified.
99 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
101 MachineInstr *CopyMI) {
102 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
104 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
105 // the example above.
106 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
107 if (BLR == IntB.end()) // Should never happen!
109 VNInfo *BValNo = BLR->valno;
111 // Get the location that B is defined at. Two options: either this value has
112 // an unknown definition point or it is defined at CopyIdx. If unknown, we
114 if (!BValNo->copy) return false;
115 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
117 // AValNo is the value number in A that defines the copy, A3 in the example.
118 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
119 if (ALR == IntA.end()) // Should never happen!
121 VNInfo *AValNo = ALR->valno;
123 // If AValNo is defined as a copy from IntB, we can potentially process this.
124 // Get the instruction that defines this value number.
125 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
126 if (!SrcReg) return false; // Not defined by a copy.
128 // If the value number is not defined by a copy instruction, ignore it.
130 // If the source register comes from an interval other than IntB, we can't
132 if (SrcReg != IntB.reg) return false;
134 // Get the LiveRange in IntB that this value number starts with.
135 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
136 if (ValLR == IntB.end()) // Should never happen!
139 // Make sure that the end of the live range is inside the same block as
141 MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
143 ValLREndInst->getParent() != CopyMI->getParent()) return false;
145 // Okay, we now know that ValLR ends in the same block that the CopyMI
146 // live-range starts. If there are no intervening live ranges between them in
147 // IntB, we can merge them.
148 if (ValLR+1 != BLR) return false;
150 // If a live interval is a physical register, conservatively check if any
151 // of its sub-registers is overlapping the live interval of the virtual
152 // register. If so, do not coalesce.
153 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
154 *tri_->getSubRegisters(IntB.reg)) {
155 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
156 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
157 DOUT << "Interfere with sub-register ";
158 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
163 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
165 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
166 // We are about to delete CopyMI, so need to remove it as the 'instruction
167 // that defines this value #'. Update the the valnum with the new defining
169 BValNo->def = FillerStart;
172 // Okay, we can merge them. We need to insert a new liverange:
173 // [ValLR.end, BLR.begin) of either value number, then we merge the
174 // two value numbers.
175 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
177 // If the IntB live range is assigned to a physical register, and if that
178 // physreg has aliases,
179 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
180 // Update the liveintervals of sub-registers.
181 for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) {
182 LiveInterval &AliasLI = li_->getInterval(*AS);
183 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
184 AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
188 // Okay, merge "B1" into the same value number as "B0".
189 if (BValNo != ValLR->valno) {
190 IntB.addKills(ValLR->valno, BValNo->kills);
191 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
193 DOUT << " result = "; IntB.print(DOUT, tri_);
196 // If the source instruction was killing the source register before the
197 // merge, unset the isKill marker given the live range has been extended.
198 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
200 ValLREndInst->getOperand(UIdx).setIsKill(false);
201 IntB.removeKill(ValLR->valno, FillerStart);
208 /// HasOtherReachingDefs - Return true if there are definitions of IntB
209 /// other than BValNo val# that can reach uses of AValno val# of IntA.
210 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
214 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
216 if (AI->valno != AValNo) continue;
217 LiveInterval::Ranges::iterator BI =
218 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
219 if (BI != IntB.ranges.begin())
221 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
222 if (BI->valno == BValNo)
224 if (BI->start <= AI->start && BI->end > AI->start)
226 if (BI->start > AI->start && BI->start < AI->end)
233 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
234 /// being the source and IntB being the dest, thus this defines a value number
235 /// in IntB. If the source value number (in IntA) is defined by a commutable
236 /// instruction and its other operand is coalesced to the copy dest register,
237 /// see if we can transform the copy into a noop by commuting the definition. For
240 /// A3 = op A2 B0<kill>
242 /// B1 = A3 <- this copy
244 /// = op A3 <- more uses
248 /// B2 = op B0 A2<kill>
250 /// B1 = B2 <- now an identify copy
252 /// = op B2 <- more uses
254 /// This returns true if an interval was modified.
256 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
258 MachineInstr *CopyMI) {
259 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
261 // FIXME: For now, only eliminate the copy by commuting its def when the
262 // source register is a virtual register. We want to guard against cases
263 // where the copy is a back edge copy and commuting the def lengthen the
264 // live interval of the source register to the entire loop.
265 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
268 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
269 // the example above.
270 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
271 if (BLR == IntB.end()) // Should never happen!
273 VNInfo *BValNo = BLR->valno;
275 // Get the location that B is defined at. Two options: either this value has
276 // an unknown definition point or it is defined at CopyIdx. If unknown, we
278 if (!BValNo->copy) return false;
279 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
281 // AValNo is the value number in A that defines the copy, A3 in the example.
282 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
283 if (ALR == IntA.end()) // Should never happen!
285 VNInfo *AValNo = ALR->valno;
286 // If other defs can reach uses of this def, then it's not safe to perform
288 if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
290 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
291 const TargetInstrDesc &TID = DefMI->getDesc();
293 if (!TID.isCommutable() ||
294 !tii_->CommuteChangesDestination(DefMI, NewDstIdx))
297 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
298 unsigned NewReg = NewDstMO.getReg();
299 if (NewReg != IntB.reg || !NewDstMO.isKill())
302 // Make sure there are no other definitions of IntB that would reach the
303 // uses which the new definition can reach.
304 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
307 // If some of the uses of IntA.reg is already coalesced away, return false.
308 // It's not possible to determine whether it's safe to perform the coalescing.
309 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
310 UE = mri_->use_end(); UI != UE; ++UI) {
311 MachineInstr *UseMI = &*UI;
312 unsigned UseIdx = li_->getInstructionIndex(UseMI);
313 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
314 if (ULR == IntA.end())
316 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
320 // At this point we have decided that it is legal to do this
321 // transformation. Start by commuting the instruction.
322 MachineBasicBlock *MBB = DefMI->getParent();
323 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
326 if (NewMI != DefMI) {
327 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
328 MBB->insert(DefMI, NewMI);
331 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
332 NewMI->getOperand(OpIdx).setIsKill();
334 bool BHasPHIKill = BValNo->hasPHIKill;
335 SmallVector<VNInfo*, 4> BDeadValNos;
336 SmallVector<unsigned, 4> BKills;
337 std::map<unsigned, unsigned> BExtend;
339 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
348 // then do not add kills of A to the newly created B interval.
349 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
351 BExtend[ALR->end] = BLR->end;
353 // Update uses of IntA of the specific Val# with IntB.
354 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
355 UE = mri_->use_end(); UI != UE;) {
356 MachineOperand &UseMO = UI.getOperand();
357 MachineInstr *UseMI = &*UI;
359 if (JoinedCopies.count(UseMI))
361 unsigned UseIdx = li_->getInstructionIndex(UseMI);
362 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
363 if (ULR == IntA.end() || ULR->valno != AValNo)
365 UseMO.setReg(NewReg);
368 if (UseMO.isKill()) {
370 UseMO.setIsKill(false);
372 BKills.push_back(li_->getUseIndex(UseIdx)+1);
374 unsigned SrcReg, DstReg;
375 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg))
377 if (DstReg == IntB.reg) {
378 // This copy will become a noop. If it's defining a new val#,
379 // remove that val# as well. However this live range is being
380 // extended to the end of the existing live range defined by the copy.
381 unsigned DefIdx = li_->getDefIndex(UseIdx);
382 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
383 BHasPHIKill |= DLR->valno->hasPHIKill;
384 assert(DLR->valno->def == DefIdx);
385 BDeadValNos.push_back(DLR->valno);
386 BExtend[DLR->start] = DLR->end;
387 JoinedCopies.insert(UseMI);
388 // If this is a kill but it's going to be removed, the last use
389 // of the same val# is the new kill.
395 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
396 // simply extend BLR if CopyMI doesn't end the range.
397 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
399 // Remove val#'s defined by copies that will be coalesced away.
400 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
401 IntB.removeValNo(BDeadValNos[i]);
403 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
404 // is updated. Kills are also updated.
405 VNInfo *ValNo = BValNo;
406 ValNo->def = AValNo->def;
408 for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) {
409 unsigned Kill = ValNo->kills[j];
410 if (Kill != BLR->end)
411 BKills.push_back(Kill);
413 ValNo->kills.clear();
414 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
416 if (AI->valno != AValNo) continue;
417 unsigned End = AI->end;
418 std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
419 if (EI != BExtend.end())
421 IntB.addRange(LiveRange(AI->start, End, ValNo));
423 IntB.addKills(ValNo, BKills);
424 ValNo->hasPHIKill = BHasPHIKill;
426 DOUT << " result = "; IntB.print(DOUT, tri_);
429 DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
430 IntA.removeValNo(AValNo);
431 DOUT << " result = "; IntA.print(DOUT, tri_);
438 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
439 /// computation, replace the copy by rematerialize the definition.
440 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
442 MachineInstr *CopyMI) {
443 unsigned CopyIdx = li_->getUseIndex(li_->getInstructionIndex(CopyMI));
444 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
445 if (SrcLR == SrcInt.end()) // Should never happen!
447 VNInfo *ValNo = SrcLR->valno;
448 // If other defs can reach uses of this def, then it's not safe to perform
450 if (ValNo->def == ~0U || ValNo->def == ~1U || ValNo->hasPHIKill)
452 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
453 const TargetInstrDesc &TID = DefMI->getDesc();
454 if (!TID.isAsCheapAsAMove())
456 bool SawStore = false;
457 if (!DefMI->isSafeToMove(tii_, SawStore))
460 unsigned DefIdx = li_->getDefIndex(CopyIdx);
461 const LiveRange *DLR= li_->getInterval(DstReg).getLiveRangeContaining(DefIdx);
462 DLR->valno->copy = NULL;
463 // Don't forget to update sub-register intervals.
464 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
465 for (const unsigned* SR = tri_->getSubRegisters(DstReg); *SR; ++SR) {
466 if (!li_->hasInterval(*SR))
468 DLR = li_->getInterval(*SR).getLiveRangeContaining(DefIdx);
469 if (DLR && DLR->valno->copy == CopyMI)
470 DLR->valno->copy = NULL;
474 MachineBasicBlock *MBB = CopyMI->getParent();
475 MachineBasicBlock::iterator MII = next(MachineBasicBlock::iterator(CopyMI));
476 CopyMI->removeFromParent();
477 tii_->reMaterialize(*MBB, MII, DstReg, DefMI);
478 MachineInstr *NewMI = prior(MII);
479 // CopyMI may have implicit operands, transfer them over to the newly
480 // rematerialized instruction. And update implicit def interval valnos.
481 for (unsigned i = CopyMI->getDesc().getNumOperands(),
482 e = CopyMI->getNumOperands(); i != e; ++i) {
483 MachineOperand &MO = CopyMI->getOperand(i);
484 if (MO.isReg() && MO.isImplicit())
485 NewMI->addOperand(MO);
486 if (MO.isDef() && li_->hasInterval(MO.getReg())) {
487 unsigned Reg = MO.getReg();
488 DLR = li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
489 if (DLR && DLR->valno->copy == CopyMI)
490 DLR->valno->copy = NULL;
494 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
495 MBB->getParent()->DeleteMachineInstr(CopyMI);
496 ReMatCopies.insert(CopyMI);
497 ReMatDefs.insert(DefMI);
502 /// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
504 bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
505 unsigned DstReg) const {
506 MachineBasicBlock *MBB = CopyMI->getParent();
507 const MachineLoop *L = loopInfo->getLoopFor(MBB);
510 if (MBB != L->getLoopLatch())
513 LiveInterval &LI = li_->getInterval(DstReg);
514 unsigned DefIdx = li_->getInstructionIndex(CopyMI);
515 LiveInterval::const_iterator DstLR =
516 LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
517 if (DstLR == LI.end())
519 unsigned KillIdx = li_->getMBBEndIdx(MBB) + 1;
520 if (DstLR->valno->kills.size() == 1 &&
521 DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
526 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
527 /// update the subregister number if it is not zero. If DstReg is a
528 /// physical register and the existing subregister number of the def / use
529 /// being updated is not zero, make sure to set it to the correct physical
532 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
534 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
535 if (DstIsPhys && SubIdx) {
536 // Figure out the real physical register we are updating with.
537 DstReg = tri_->getSubReg(DstReg, SubIdx);
541 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
542 E = mri_->reg_end(); I != E; ) {
543 MachineOperand &O = I.getOperand();
544 MachineInstr *UseMI = &*I;
546 unsigned OldSubIdx = O.getSubReg();
548 unsigned UseDstReg = DstReg;
550 UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
552 unsigned CopySrcReg, CopyDstReg;
553 if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg) &&
554 CopySrcReg != CopyDstReg &&
555 CopySrcReg == SrcReg && CopyDstReg != UseDstReg) {
556 // If the use is a copy and it won't be coalesced away, and its source
557 // is defined by a trivial computation, try to rematerialize it instead.
558 if (ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg,UseMI))
567 // Sub-register indexes goes from small to large. e.g.
568 // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
569 // EAX: 1 -> AL, 2 -> AX
570 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
571 // sub-register 2 is also AX.
572 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
573 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
576 // Remove would-be duplicated kill marker.
577 if (O.isKill() && UseMI->killsRegister(DstReg))
581 // After updating the operand, check if the machine instruction has
582 // become a copy. If so, update its val# information.
583 const TargetInstrDesc &TID = UseMI->getDesc();
584 unsigned CopySrcReg, CopyDstReg;
585 if (TID.getNumDefs() == 1 && TID.getNumOperands() > 2 &&
586 tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg) &&
587 CopySrcReg != CopyDstReg &&
588 (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
589 allocatableRegs_[CopyDstReg])) {
590 LiveInterval &LI = li_->getInterval(CopyDstReg);
591 unsigned DefIdx = li_->getDefIndex(li_->getInstructionIndex(UseMI));
592 const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx);
593 if (DLR->valno->def == DefIdx)
594 DLR->valno->copy = UseMI;
599 /// RemoveDeadImpDef - Remove implicit_def instructions which are "re-defining"
600 /// registers due to insert_subreg coalescing. e.g.
602 /// r1025 = implicit_def
603 /// r1025 = insert_subreg r1025, r1024
607 /// r1025 = implicit_def
608 /// r1025 = insert_subreg r1025, r1025
611 SimpleRegisterCoalescing::RemoveDeadImpDef(unsigned Reg, LiveInterval &LI) {
612 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
613 E = mri_->reg_end(); I != E; ) {
614 MachineOperand &O = I.getOperand();
615 MachineInstr *DefMI = &*I;
619 if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
621 if (!LI.liveBeforeAndAt(li_->getInstructionIndex(DefMI)))
623 li_->RemoveMachineInstrFromMaps(DefMI);
624 DefMI->eraseFromParent();
628 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
629 /// due to live range lengthening as the result of coalescing.
630 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
632 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
633 UE = mri_->use_end(); UI != UE; ++UI) {
634 MachineOperand &UseMO = UI.getOperand();
635 if (UseMO.isKill()) {
636 MachineInstr *UseMI = UseMO.getParent();
637 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
638 if (JoinedCopies.count(UseMI))
640 const LiveRange *UI = LI.getLiveRangeContaining(UseIdx);
641 if (!UI || !LI.isKill(UI->valno, UseIdx+1))
642 UseMO.setIsKill(false);
647 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
648 /// from a physical register live interval as well as from the live intervals
649 /// of its sub-registers.
650 static void removeRange(LiveInterval &li, unsigned Start, unsigned End,
651 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
652 li.removeRange(Start, End, true);
653 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
654 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
655 if (!li_->hasInterval(*SR))
657 LiveInterval &sli = li_->getInterval(*SR);
658 unsigned RemoveEnd = Start;
659 while (RemoveEnd != End) {
660 LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
663 RemoveEnd = (LR->end < End) ? LR->end : End;
664 sli.removeRange(Start, RemoveEnd, true);
671 /// removeIntervalIfEmpty - Check if the live interval of a physical register
672 /// is empty, if so remove it and also remove the empty intervals of its
673 /// sub-registers. Return true if live interval is removed.
674 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
675 const TargetRegisterInfo *tri_) {
677 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
678 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
679 if (!li_->hasInterval(*SR))
681 LiveInterval &sli = li_->getInterval(*SR);
683 li_->removeInterval(*SR);
685 li_->removeInterval(li.reg);
691 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
692 /// Return true if live interval is removed.
693 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
694 MachineInstr *CopyMI) {
695 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
696 LiveInterval::iterator MLR =
697 li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
699 return false; // Already removed by ShortenDeadCopySrcLiveRange.
700 unsigned RemoveStart = MLR->start;
701 unsigned RemoveEnd = MLR->end;
702 // Remove the liverange that's defined by this.
703 if (RemoveEnd == li_->getDefIndex(CopyIdx)+1) {
704 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
705 return removeIntervalIfEmpty(li, li_, tri_);
710 /// PropagateDeadness - Propagate the dead marker to the instruction which
711 /// defines the val#.
712 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
713 unsigned &LRStart, LiveIntervals *li_,
714 const TargetRegisterInfo* tri_) {
715 MachineInstr *DefMI =
716 li_->getInstructionFromIndex(li_->getDefIndex(LRStart));
717 if (DefMI && DefMI != CopyMI) {
718 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false, tri_);
720 DefMI->getOperand(DeadIdx).setIsDead();
721 // A dead def should have a single cycle interval.
727 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
728 /// fallthoughs to SuccMBB.
729 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
730 MachineBasicBlock *SuccMBB,
731 const TargetInstrInfo *tii_) {
734 MachineBasicBlock *TBB = 0, *FBB = 0;
735 SmallVector<MachineOperand, 4> Cond;
736 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
737 MBB->isSuccessor(SuccMBB);
740 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
741 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
742 /// ends the live range there. If there isn't another use, then this live range
743 /// is dead. Return true if live interval is removed.
745 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
746 MachineInstr *CopyMI) {
747 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
749 // FIXME: special case: function live in. It can be a general case if the
750 // first instruction index starts at > 0 value.
751 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
752 // Live-in to the function but dead. Remove it from entry live-in set.
753 if (mf_->begin()->isLiveIn(li.reg))
754 mf_->begin()->removeLiveIn(li.reg);
755 const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
756 removeRange(li, LR->start, LR->end, li_, tri_);
757 return removeIntervalIfEmpty(li, li_, tri_);
760 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx-1);
762 // Livein but defined by a phi.
765 unsigned RemoveStart = LR->start;
766 unsigned RemoveEnd = li_->getDefIndex(CopyIdx)+1;
767 if (LR->end > RemoveEnd)
768 // More uses past this copy? Nothing to do.
771 MachineBasicBlock *CopyMBB = CopyMI->getParent();
772 unsigned MBBStart = li_->getMBBStartIdx(CopyMBB);
774 MachineOperand *LastUse = lastRegisterUse(LR->start, CopyIdx-1, li.reg,
777 MachineInstr *LastUseMI = LastUse->getParent();
778 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
785 // r1025<dead> = r1024<kill>
786 if (MBBStart < LR->end)
787 removeRange(li, MBBStart, LR->end, li_, tri_);
791 // There are uses before the copy, just shorten the live range to the end
793 LastUse->setIsKill();
794 removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
795 unsigned SrcReg, DstReg;
796 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg) &&
798 // Last use is itself an identity code.
799 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
800 LastUseMI->getOperand(DeadIdx).setIsDead();
806 if (LR->start <= MBBStart && LR->end > MBBStart) {
807 if (LR->start == 0) {
808 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
809 // Live-in to the function but dead. Remove it from entry live-in set.
810 mf_->begin()->removeLiveIn(li.reg);
812 // FIXME: Shorten intervals in BBs that reaches this BB.
815 if (LR->valno->def == RemoveStart)
816 // If the def MI defines the val#, propagate the dead marker.
817 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
819 removeRange(li, RemoveStart, LR->end, li_, tri_);
820 return removeIntervalIfEmpty(li, li_, tri_);
823 /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
824 /// from an implicit def to another register can be coalesced away.
825 bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
827 LiveInterval &ImpLi) const{
828 if (!CopyMI->killsRegister(ImpLi.reg))
830 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
831 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx);
834 if (LR->valno->hasPHIKill)
836 if (LR->valno->def != CopyIdx)
838 // Make sure all of val# uses are copies.
839 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(li.reg),
840 UE = mri_->use_end(); UI != UE;) {
841 MachineInstr *UseMI = &*UI;
843 if (JoinedCopies.count(UseMI))
845 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
846 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
847 if (ULR == li.end() || ULR->valno != LR->valno)
849 // If the use is not a use, then it's not safe to coalesce the move.
850 unsigned SrcReg, DstReg;
851 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg)) {
852 if (UseMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG &&
853 UseMI->getOperand(1).getReg() == li.reg)
862 /// RemoveCopiesFromValNo - The specified value# is defined by an implicit
863 /// def and it is being removed. Turn all copies from this value# into
864 /// identity copies so they will be removed.
865 void SimpleRegisterCoalescing::RemoveCopiesFromValNo(LiveInterval &li,
867 SmallVector<MachineInstr*, 4> ImpDefs;
868 MachineOperand *LastUse = NULL;
869 unsigned LastUseIdx = li_->getUseIndex(VNI->def);
870 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg),
871 RE = mri_->reg_end(); RI != RE;) {
872 MachineOperand *MO = &RI.getOperand();
873 MachineInstr *MI = &*RI;
876 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
877 ImpDefs.push_back(MI);
881 if (JoinedCopies.count(MI))
883 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(MI));
884 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
885 if (ULR == li.end() || ULR->valno != VNI)
887 // If the use is a copy, turn it into an identity copy.
888 unsigned SrcReg, DstReg;
889 if (tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == li.reg) {
890 // Each use MI may have multiple uses of this register. Change them all.
891 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
892 MachineOperand &MO = MI->getOperand(i);
893 if (MO.isReg() && MO.getReg() == li.reg)
896 JoinedCopies.insert(MI);
897 } else if (UseIdx > LastUseIdx) {
903 LastUse->setIsKill();
905 // Remove dead implicit_def's.
906 while (!ImpDefs.empty()) {
907 MachineInstr *ImpDef = ImpDefs.back();
909 li_->RemoveMachineInstrFromMaps(ImpDef);
910 ImpDef->eraseFromParent();
915 /// getMatchingSuperReg - Return a super-register of the specified register
916 /// Reg so its sub-register of index SubIdx is Reg.
917 static unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
918 const TargetRegisterClass *RC,
919 const TargetRegisterInfo* TRI) {
920 for (const unsigned *SRs = TRI->getSuperRegisters(Reg);
921 unsigned SR = *SRs; ++SRs)
922 if (Reg == TRI->getSubReg(SR, SubIdx) && RC->contains(SR))
927 /// isProfitableToCoalesceToSubRC - Given that register class of DstReg is
928 /// a subset of the register class of SrcReg, return true if it's profitable
929 /// to coalesce the two registers.
931 SimpleRegisterCoalescing::isProfitableToCoalesceToSubRC(unsigned SrcReg,
933 MachineBasicBlock *MBB){
937 // First let's make sure all uses are in the same MBB.
938 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(SrcReg),
939 RE = mri_->reg_end(); RI != RE; ++RI) {
940 MachineInstr &MI = *RI;
941 if (MI.getParent() != MBB)
944 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(DstReg),
945 RE = mri_->reg_end(); RI != RE; ++RI) {
946 MachineInstr &MI = *RI;
947 if (MI.getParent() != MBB)
951 // Then make sure the intervals are *short*.
952 LiveInterval &SrcInt = li_->getInterval(SrcReg);
953 LiveInterval &DstInt = li_->getInterval(DstReg);
954 unsigned SrcSize = li_->getApproximateInstructionCount(SrcInt);
955 unsigned DstSize = li_->getApproximateInstructionCount(DstInt);
956 const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
957 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
958 return (SrcSize + DstSize) <= Threshold;
961 /// HasIncompatibleSubRegDefUse - If we are trying to coalesce a virtual
962 /// register with a physical register, check if any of the virtual register
963 /// operand is a sub-register use or def. If so, make sure it won't result
964 /// in an illegal extract_subreg or insert_subreg instruction. e.g.
965 /// vr1024 = extract_subreg vr1025, 1
967 /// vr1024 = mov8rr AH
968 /// If vr1024 is coalesced with AH, the extract_subreg is now illegal since
969 /// AH does not have a super-reg whose sub-register 1 is AH.
971 SimpleRegisterCoalescing::HasIncompatibleSubRegDefUse(MachineInstr *CopyMI,
974 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(VirtReg),
975 E = mri_->reg_end(); I != E; ++I) {
976 MachineOperand &O = I.getOperand();
977 MachineInstr *MI = &*I;
978 if (MI == CopyMI || JoinedCopies.count(MI))
980 unsigned SubIdx = O.getSubReg();
981 if (SubIdx && !tri_->getSubReg(PhysReg, SubIdx))
983 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
984 SubIdx = MI->getOperand(2).getImm();
985 if (O.isUse() && !tri_->getSubReg(PhysReg, SubIdx))
988 unsigned SrcReg = MI->getOperand(1).getReg();
989 const TargetRegisterClass *RC =
990 TargetRegisterInfo::isPhysicalRegister(SrcReg)
991 ? tri_->getPhysicalRegisterRegClass(SrcReg)
992 : mri_->getRegClass(SrcReg);
993 if (!getMatchingSuperReg(PhysReg, SubIdx, RC, tri_))
997 if (MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
998 SubIdx = MI->getOperand(3).getImm();
999 if (VirtReg == MI->getOperand(0).getReg()) {
1000 if (!tri_->getSubReg(PhysReg, SubIdx))
1003 unsigned DstReg = MI->getOperand(0).getReg();
1004 const TargetRegisterClass *RC =
1005 TargetRegisterInfo::isPhysicalRegister(DstReg)
1006 ? tri_->getPhysicalRegisterRegClass(DstReg)
1007 : mri_->getRegClass(DstReg);
1008 if (!getMatchingSuperReg(PhysReg, SubIdx, RC, tri_))
1017 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1018 /// which are the src/dst of the copy instruction CopyMI. This returns true
1019 /// if the copy was successfully coalesced away. If it is not currently
1020 /// possible to coalesce this interval, but it may be possible if other
1021 /// things get coalesced, then it returns true by reference in 'Again'.
1022 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1023 MachineInstr *CopyMI = TheCopy.MI;
1026 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1027 return false; // Already done.
1029 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
1033 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
1034 bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG;
1035 unsigned SubIdx = 0;
1037 DstReg = CopyMI->getOperand(0).getReg();
1038 SrcReg = CopyMI->getOperand(1).getReg();
1039 } else if (isInsSubReg) {
1040 if (CopyMI->getOperand(2).getSubReg()) {
1041 DOUT << "\tSource of insert_subreg is already coalesced "
1042 << "to another register.\n";
1043 return false; // Not coalescable.
1045 DstReg = CopyMI->getOperand(0).getReg();
1046 SrcReg = CopyMI->getOperand(2).getReg();
1047 } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
1048 assert(0 && "Unrecognized copy instruction!");
1052 // If they are already joined we continue.
1053 if (SrcReg == DstReg) {
1054 DOUT << "\tCopy already coalesced.\n";
1055 return false; // Not coalescable.
1058 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1059 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1061 // If they are both physical registers, we cannot join them.
1062 if (SrcIsPhys && DstIsPhys) {
1063 DOUT << "\tCan not coalesce physregs.\n";
1064 return false; // Not coalescable.
1067 // We only join virtual registers with allocatable physical registers.
1068 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
1069 DOUT << "\tSrc reg is unallocatable physreg.\n";
1070 return false; // Not coalescable.
1072 if (DstIsPhys && !allocatableRegs_[DstReg]) {
1073 DOUT << "\tDst reg is unallocatable physreg.\n";
1074 return false; // Not coalescable.
1077 // Should be non-null only when coalescing to a sub-register class.
1078 const TargetRegisterClass *SubRC = NULL;
1079 MachineBasicBlock *CopyMBB = CopyMI->getParent();
1080 unsigned RealDstReg = 0;
1081 unsigned RealSrcReg = 0;
1082 if (isExtSubReg || isInsSubReg) {
1083 SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
1084 if (SrcIsPhys && isExtSubReg) {
1085 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
1086 // coalesced with AX.
1087 unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
1089 // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
1090 // coalesced to a larger register so the subreg indices cancel out.
1091 if (DstSubIdx != SubIdx) {
1092 DOUT << "\t Sub-register indices mismatch.\n";
1093 return false; // Not coalescable.
1096 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
1098 } else if (DstIsPhys && isInsSubReg) {
1099 // EAX = INSERT_SUBREG EAX, r1024, 0
1100 unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1102 // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
1103 // coalesced to a larger register so the subreg indices cancel out.
1104 if (SrcSubIdx != SubIdx) {
1105 DOUT << "\t Sub-register indices mismatch.\n";
1106 return false; // Not coalescable.
1109 DstReg = tri_->getSubReg(DstReg, SubIdx);
1111 } else if ((DstIsPhys && isExtSubReg) || (SrcIsPhys && isInsSubReg)) {
1112 // If this is a extract_subreg where dst is a physical register, e.g.
1113 // cl = EXTRACT_SUBREG reg1024, 1
1114 // then create and update the actual physical register allocated to RHS.
1116 // reg1024 = INSERT_SUBREG r1024, cl, 1
1117 if (CopyMI->getOperand(1).getSubReg()) {
1118 DOUT << "\tSrc of extract_ / insert_subreg already coalesced with reg"
1119 << " of a super-class.\n";
1120 return false; // Not coalescable.
1122 const TargetRegisterClass *RC =
1123 mri_->getRegClass(isExtSubReg ? SrcReg : DstReg);
1125 RealDstReg = getMatchingSuperReg(DstReg, SubIdx, RC, tri_);
1126 assert(RealDstReg && "Invalid extract_subreg instruction!");
1128 RealSrcReg = getMatchingSuperReg(SrcReg, SubIdx, RC, tri_);
1129 assert(RealSrcReg && "Invalid extract_subreg instruction!");
1132 // For this type of EXTRACT_SUBREG, conservatively
1133 // check if the live interval of the source register interfere with the
1134 // actual super physical register we are trying to coalesce with.
1135 unsigned PhysReg = isExtSubReg ? RealDstReg : RealSrcReg;
1136 LiveInterval &RHS = li_->getInterval(isExtSubReg ? SrcReg : DstReg);
1137 if (li_->hasInterval(PhysReg) &&
1138 RHS.overlaps(li_->getInterval(PhysReg))) {
1139 DOUT << "Interfere with register ";
1140 DEBUG(li_->getInterval(PhysReg).print(DOUT, tri_));
1141 return false; // Not coalescable
1143 for (const unsigned* SR = tri_->getSubRegisters(PhysReg); *SR; ++SR)
1144 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1145 DOUT << "Interfere with sub-register ";
1146 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1147 return false; // Not coalescable
1151 unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
1152 : CopyMI->getOperand(2).getSubReg();
1154 if (OldSubIdx == SubIdx &&
1155 !differingRegisterClasses(SrcReg, DstReg, SubRC))
1156 // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
1157 // coalesced to a larger register so the subreg indices cancel out.
1158 // Also check if the other larger register is of the same register
1159 // class as the would be resulting register.
1162 DOUT << "\t Sub-register indices mismatch.\n";
1163 return false; // Not coalescable.
1167 unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
1168 unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
1169 unsigned LargeRegSize =
1170 li_->getApproximateInstructionCount(li_->getInterval(LargeReg));
1171 unsigned SmallRegSize =
1172 li_->getApproximateInstructionCount(li_->getInterval(SmallReg));
1173 const TargetRegisterClass *RC = mri_->getRegClass(SmallReg);
1174 unsigned Threshold = allocatableRCRegs_[RC].count();
1175 // Be conservative. If both sides are virtual registers, do not coalesce
1176 // if this will cause a high use density interval to target a smaller
1177 // set of registers.
1178 if (SmallRegSize > Threshold || LargeRegSize > Threshold) {
1179 if ((float)std::distance(mri_->use_begin(SmallReg),
1180 mri_->use_end()) / SmallRegSize <
1181 (float)std::distance(mri_->use_begin(LargeReg),
1182 mri_->use_end()) / LargeRegSize) {
1183 Again = true; // May be possible to coalesce later.
1189 } else if (differingRegisterClasses(SrcReg, DstReg, SubRC)) {
1190 // FIXME: What if the resul of a EXTRACT_SUBREG is then coalesced
1191 // with another? If it's the resulting destination register, then
1192 // the subidx must be propagated to uses (but only those defined
1193 // by the EXTRACT_SUBREG). If it's being coalesced into another
1194 // register, it should be safe because register is assumed to have
1195 // the register class of the super-register.
1197 if (!SubRC || !isProfitableToCoalesceToSubRC(SrcReg, DstReg, CopyMBB)) {
1198 // If they are not of the same register class, we cannot join them.
1199 DOUT << "\tSrc/Dest are different register classes.\n";
1200 // Allow the coalescer to try again in case either side gets coalesced to
1201 // a physical register that's compatible with the other side. e.g.
1202 // r1024 = MOV32to32_ r1025
1203 // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
1204 Again = true; // May be possible to coalesce later.
1209 // Will it create illegal extract_subreg / insert_subreg?
1210 if (SrcIsPhys && HasIncompatibleSubRegDefUse(CopyMI, DstReg, SrcReg))
1212 if (DstIsPhys && HasIncompatibleSubRegDefUse(CopyMI, SrcReg, DstReg))
1215 LiveInterval &SrcInt = li_->getInterval(SrcReg);
1216 LiveInterval &DstInt = li_->getInterval(DstReg);
1217 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
1218 "Register mapping is horribly broken!");
1220 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
1221 DOUT << " and "; DstInt.print(DOUT, tri_);
1224 // Check if it is necessary to propagate "isDead" property.
1225 if (!isExtSubReg && !isInsSubReg) {
1226 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1227 bool isDead = mopd->isDead();
1229 // We need to be careful about coalescing a source physical register with a
1230 // virtual register. Once the coalescing is done, it cannot be broken and
1231 // these are not spillable! If the destination interval uses are far away,
1232 // think twice about coalescing them!
1233 if (!isDead && (SrcIsPhys || DstIsPhys)) {
1234 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1235 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1236 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1237 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1238 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1239 if (TheCopy.isBackEdge)
1240 Threshold *= 2; // Favors back edge copies.
1242 // If the virtual register live interval is long but it has low use desity,
1243 // do not join them, instead mark the physical register as its allocation
1245 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1246 if (Length > Threshold &&
1247 (((float)std::distance(mri_->use_begin(JoinVReg),
1248 mri_->use_end()) / Length) < (1.0 / Threshold))) {
1249 JoinVInt.preference = JoinPReg;
1251 DOUT << "\tMay tie down a physical register, abort!\n";
1252 Again = true; // May be possible to coalesce later.
1258 // Okay, attempt to join these two intervals. On failure, this returns false.
1259 // Otherwise, if one of the intervals being joined is a physreg, this method
1260 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1261 // been modified, so we can use this information below to update aliases.
1262 bool Swapped = false;
1263 // If SrcInt is implicitly defined, it's safe to coalesce.
1264 bool isEmpty = SrcInt.empty();
1265 if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
1266 // Only coalesce an empty interval (defined by implicit_def) with
1267 // another interval which has a valno defined by the CopyMI and the CopyMI
1268 // is a kill of the implicit def.
1269 DOUT << "Not profitable!\n";
1273 if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
1274 // Coalescing failed.
1276 // If definition of source is defined by trivial computation, try
1277 // rematerializing it.
1278 if (!isExtSubReg && !isInsSubReg &&
1279 ReMaterializeTrivialDef(SrcInt, DstInt.reg, CopyMI))
1282 // If we can eliminate the copy without merging the live ranges, do so now.
1283 if (!isExtSubReg && !isInsSubReg &&
1284 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1285 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
1286 JoinedCopies.insert(CopyMI);
1290 // Otherwise, we are unable to join the intervals.
1291 DOUT << "Interference!\n";
1292 Again = true; // May be possible to coalesce later.
1296 LiveInterval *ResSrcInt = &SrcInt;
1297 LiveInterval *ResDstInt = &DstInt;
1299 std::swap(SrcReg, DstReg);
1300 std::swap(ResSrcInt, ResDstInt);
1302 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1303 "LiveInterval::join didn't work right!");
1305 // If we're about to merge live ranges into a physical register live range,
1306 // we have to update any aliased register's live ranges to indicate that they
1307 // have clobbered values for this range.
1308 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1309 // If this is a extract_subreg where dst is a physical register, e.g.
1310 // cl = EXTRACT_SUBREG reg1024, 1
1311 // then create and update the actual physical register allocated to RHS.
1312 if (RealDstReg || RealSrcReg) {
1313 LiveInterval &RealInt =
1314 li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
1315 SmallSet<const VNInfo*, 4> CopiedValNos;
1316 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
1317 E = ResSrcInt->ranges.end(); I != E; ++I) {
1318 const LiveRange *DstLR = ResDstInt->getLiveRangeContaining(I->start);
1319 assert(DstLR && "Invalid joined interval!");
1320 const VNInfo *DstValNo = DstLR->valno;
1321 if (CopiedValNos.insert(DstValNo)) {
1322 VNInfo *ValNo = RealInt.getNextValue(DstValNo->def, DstValNo->copy,
1323 li_->getVNInfoAllocator());
1324 ValNo->hasPHIKill = DstValNo->hasPHIKill;
1325 RealInt.addKills(ValNo, DstValNo->kills);
1326 RealInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
1330 DstReg = RealDstReg ? RealDstReg : RealSrcReg;
1333 // Update the liveintervals of sub-registers.
1334 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
1335 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
1336 li_->getVNInfoAllocator());
1339 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1340 // larger super-register.
1341 if ((isExtSubReg || isInsSubReg) && !SrcIsPhys && !DstIsPhys) {
1342 if ((isExtSubReg && !Swapped) || (isInsSubReg && Swapped)) {
1343 ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
1344 std::swap(SrcReg, DstReg);
1345 std::swap(ResSrcInt, ResDstInt);
1349 // Coalescing to a virtual register that is of a sub-register class of the
1350 // other. Make sure the resulting register is set to the right register class.
1352 mri_->setRegClass(DstReg, SubRC);
1357 // Add all copies that define val# in the source interval into the queue.
1358 for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
1359 e = ResSrcInt->vni_end(); i != e; ++i) {
1360 const VNInfo *vni = *i;
1361 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
1363 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
1364 unsigned NewSrcReg, NewDstReg;
1366 JoinedCopies.count(CopyMI) == 0 &&
1367 tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg)) {
1368 unsigned LoopDepth = loopInfo->getLoopDepth(CopyMBB);
1369 JoinQueue->push(CopyRec(CopyMI, LoopDepth,
1370 isBackEdgeCopy(CopyMI, DstReg)));
1375 // Remember to delete the copy instruction.
1376 JoinedCopies.insert(CopyMI);
1378 // Some live range has been lengthened due to colaescing, eliminate the
1379 // unnecessary kills.
1380 RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1381 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1382 RemoveUnnecessaryKills(DstReg, *ResDstInt);
1387 // r1024 = implicit_def
1390 RemoveDeadImpDef(DstReg, *ResDstInt);
1391 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1393 // SrcReg is guarateed to be the register whose live interval that is
1395 li_->removeInterval(SrcReg);
1398 // Now the copy is being coalesced away, the val# previously defined
1399 // by the copy is being defined by an IMPLICIT_DEF which defines a zero
1400 // length interval. Remove the val#.
1401 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1402 const LiveRange *LR = ResDstInt->getLiveRangeContaining(CopyIdx);
1403 VNInfo *ImpVal = LR->valno;
1404 assert(ImpVal->def == CopyIdx);
1405 unsigned NextDef = LR->end;
1406 RemoveCopiesFromValNo(*ResDstInt, ImpVal);
1407 ResDstInt->removeValNo(ImpVal);
1408 LR = ResDstInt->FindLiveRangeContaining(NextDef);
1409 if (LR != ResDstInt->end() && LR->valno->def == NextDef) {
1410 // Special case: vr1024 = implicit_def
1411 // vr1024 = insert_subreg vr1024, vr1025, c
1412 // The insert_subreg becomes a "copy" that defines a val# which can itself
1413 // be coalesced away.
1414 MachineInstr *DefMI = li_->getInstructionFromIndex(NextDef);
1415 if (DefMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
1416 LR->valno->copy = DefMI;
1420 // If resulting interval has a preference that no longer fits because of subreg
1421 // coalescing, just clear the preference.
1422 if (ResDstInt->preference && (isExtSubReg || isInsSubReg) &&
1423 TargetRegisterInfo::isVirtualRegister(ResDstInt->reg)) {
1424 const TargetRegisterClass *RC = mri_->getRegClass(ResDstInt->reg);
1425 if (!RC->contains(ResDstInt->preference))
1426 ResDstInt->preference = 0;
1429 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, tri_);
1436 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1437 /// compute what the resultant value numbers for each value in the input two
1438 /// ranges will be. This is complicated by copies between the two which can
1439 /// and will commonly cause multiple value numbers to be merged into one.
1441 /// VN is the value number that we're trying to resolve. InstDefiningValue
1442 /// keeps track of the new InstDefiningValue assignment for the result
1443 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1444 /// whether a value in this or other is a copy from the opposite set.
1445 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1446 /// already been assigned.
1448 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1449 /// contains the value number the copy is from.
1451 static unsigned ComputeUltimateVN(VNInfo *VNI,
1452 SmallVector<VNInfo*, 16> &NewVNInfo,
1453 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1454 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1455 SmallVector<int, 16> &ThisValNoAssignments,
1456 SmallVector<int, 16> &OtherValNoAssignments) {
1457 unsigned VN = VNI->id;
1459 // If the VN has already been computed, just return it.
1460 if (ThisValNoAssignments[VN] >= 0)
1461 return ThisValNoAssignments[VN];
1462 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
1464 // If this val is not a copy from the other val, then it must be a new value
1465 // number in the destination.
1466 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1467 if (I == ThisFromOther.end()) {
1468 NewVNInfo.push_back(VNI);
1469 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1471 VNInfo *OtherValNo = I->second;
1473 // Otherwise, this *is* a copy from the RHS. If the other side has already
1474 // been computed, return it.
1475 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1476 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1478 // Mark this value number as currently being computed, then ask what the
1479 // ultimate value # of the other value is.
1480 ThisValNoAssignments[VN] = -2;
1481 unsigned UltimateVN =
1482 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1483 OtherValNoAssignments, ThisValNoAssignments);
1484 return ThisValNoAssignments[VN] = UltimateVN;
1487 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
1488 return std::find(V.begin(), V.end(), Val) != V.end();
1491 /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1492 /// the specified live interval is defined by a copy from the specified
1494 bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1497 unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1500 if (LR->valno->def == ~0U &&
1501 TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1502 *tri_->getSuperRegisters(li.reg)) {
1503 // It's a sub-register live interval, we may not have precise information.
1505 MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1506 unsigned SrcReg, DstReg;
1507 if (DefMI && tii_->isMoveInstr(*DefMI, SrcReg, DstReg) &&
1508 DstReg == li.reg && SrcReg == Reg) {
1509 // Cache computed info.
1510 LR->valno->def = LR->start;
1511 LR->valno->copy = DefMI;
1518 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1519 /// caller of this method must guarantee that the RHS only contains a single
1520 /// value number and that the RHS is not defined by a copy from this
1521 /// interval. This returns false if the intervals are not joinable, or it
1522 /// joins them and returns true.
1523 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
1524 assert(RHS.containsOneValue());
1526 // Some number (potentially more than one) value numbers in the current
1527 // interval may be defined as copies from the RHS. Scan the overlapping
1528 // portions of the LHS and RHS, keeping track of this and looking for
1529 // overlapping live ranges that are NOT defined as copies. If these exist, we
1532 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1533 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1535 if (LHSIt->start < RHSIt->start) {
1536 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1537 if (LHSIt != LHS.begin()) --LHSIt;
1538 } else if (RHSIt->start < LHSIt->start) {
1539 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1540 if (RHSIt != RHS.begin()) --RHSIt;
1543 SmallVector<VNInfo*, 8> EliminatedLHSVals;
1546 // Determine if these live intervals overlap.
1547 bool Overlaps = false;
1548 if (LHSIt->start <= RHSIt->start)
1549 Overlaps = LHSIt->end > RHSIt->start;
1551 Overlaps = RHSIt->end > LHSIt->start;
1553 // If the live intervals overlap, there are two interesting cases: if the
1554 // LHS interval is defined by a copy from the RHS, it's ok and we record
1555 // that the LHS value # is the same as the RHS. If it's not, then we cannot
1556 // coalesce these live ranges and we bail out.
1558 // If we haven't already recorded that this value # is safe, check it.
1559 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
1560 // Copy from the RHS?
1561 if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
1562 return false; // Nope, bail out.
1564 if (LHSIt->contains(RHSIt->valno->def))
1565 // Here is an interesting situation:
1567 // vr1025 = copy vr1024
1572 // Even though vr1025 is copied from vr1024, it's not safe to
1573 // coalesced them since live range of vr1025 intersects the
1574 // def of vr1024. This happens because vr1025 is assigned the
1575 // value of the previous iteration of vr1024.
1577 EliminatedLHSVals.push_back(LHSIt->valno);
1580 // We know this entire LHS live range is okay, so skip it now.
1581 if (++LHSIt == LHSEnd) break;
1585 if (LHSIt->end < RHSIt->end) {
1586 if (++LHSIt == LHSEnd) break;
1588 // One interesting case to check here. It's possible that we have
1589 // something like "X3 = Y" which defines a new value number in the LHS,
1590 // and is the last use of this liverange of the RHS. In this case, we
1591 // want to notice this copy (so that it gets coalesced away) even though
1592 // the live ranges don't actually overlap.
1593 if (LHSIt->start == RHSIt->end) {
1594 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
1595 // We already know that this value number is going to be merged in
1596 // if coalescing succeeds. Just skip the liverange.
1597 if (++LHSIt == LHSEnd) break;
1599 // Otherwise, if this is a copy from the RHS, mark it as being merged
1601 if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
1602 if (LHSIt->contains(RHSIt->valno->def))
1603 // Here is an interesting situation:
1605 // vr1025 = copy vr1024
1610 // Even though vr1025 is copied from vr1024, it's not safe to
1611 // coalesced them since live range of vr1025 intersects the
1612 // def of vr1024. This happens because vr1025 is assigned the
1613 // value of the previous iteration of vr1024.
1615 EliminatedLHSVals.push_back(LHSIt->valno);
1617 // We know this entire LHS live range is okay, so skip it now.
1618 if (++LHSIt == LHSEnd) break;
1623 if (++RHSIt == RHSEnd) break;
1627 // If we got here, we know that the coalescing will be successful and that
1628 // the value numbers in EliminatedLHSVals will all be merged together. Since
1629 // the most common case is that EliminatedLHSVals has a single number, we
1630 // optimize for it: if there is more than one value, we merge them all into
1631 // the lowest numbered one, then handle the interval as if we were merging
1632 // with one value number.
1634 if (EliminatedLHSVals.size() > 1) {
1635 // Loop through all the equal value numbers merging them into the smallest
1637 VNInfo *Smallest = EliminatedLHSVals[0];
1638 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1639 if (EliminatedLHSVals[i]->id < Smallest->id) {
1640 // Merge the current notion of the smallest into the smaller one.
1641 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1642 Smallest = EliminatedLHSVals[i];
1644 // Merge into the smallest.
1645 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1648 LHSValNo = Smallest;
1649 } else if (EliminatedLHSVals.empty()) {
1650 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1651 *tri_->getSuperRegisters(LHS.reg))
1652 // Imprecise sub-register information. Can't handle it.
1654 assert(0 && "No copies from the RHS?");
1656 LHSValNo = EliminatedLHSVals[0];
1659 // Okay, now that there is a single LHS value number that we're merging the
1660 // RHS into, update the value number info for the LHS to indicate that the
1661 // value number is defined where the RHS value number was.
1662 const VNInfo *VNI = RHS.getValNumInfo(0);
1663 LHSValNo->def = VNI->def;
1664 LHSValNo->copy = VNI->copy;
1666 // Okay, the final step is to loop over the RHS live intervals, adding them to
1668 LHSValNo->hasPHIKill |= VNI->hasPHIKill;
1669 LHS.addKills(LHSValNo, VNI->kills);
1670 LHS.MergeRangesInAsValue(RHS, LHSValNo);
1671 LHS.weight += RHS.weight;
1672 if (RHS.preference && !LHS.preference)
1673 LHS.preference = RHS.preference;
1678 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1679 /// returns false. Otherwise, if one of the intervals being joined is a
1680 /// physreg, this method always canonicalizes LHS to be it. The output
1681 /// "RHS" will not have been modified, so we can use this information
1682 /// below to update aliases.
1683 bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
1684 LiveInterval &RHS, bool &Swapped) {
1685 // Compute the final value assignment, assuming that the live ranges can be
1687 SmallVector<int, 16> LHSValNoAssignments;
1688 SmallVector<int, 16> RHSValNoAssignments;
1689 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1690 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1691 SmallVector<VNInfo*, 16> NewVNInfo;
1693 // If a live interval is a physical register, conservatively check if any
1694 // of its sub-registers is overlapping the live interval of the virtual
1695 // register. If so, do not coalesce.
1696 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1697 *tri_->getSubRegisters(LHS.reg)) {
1698 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
1699 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1700 DOUT << "Interfere with sub-register ";
1701 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1704 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1705 *tri_->getSubRegisters(RHS.reg)) {
1706 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
1707 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1708 DOUT << "Interfere with sub-register ";
1709 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1714 // Compute ultimate value numbers for the LHS and RHS values.
1715 if (RHS.containsOneValue()) {
1716 // Copies from a liveinterval with a single value are simple to handle and
1717 // very common, handle the special case here. This is important, because
1718 // often RHS is small and LHS is large (e.g. a physreg).
1720 // Find out if the RHS is defined as a copy from some value in the LHS.
1721 int RHSVal0DefinedFromLHS = -1;
1723 VNInfo *RHSValNoInfo = NULL;
1724 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
1725 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
1726 if ((RHSSrcReg == 0 || RHSSrcReg != LHS.reg)) {
1727 // If RHS is not defined as a copy from the LHS, we can use simpler and
1728 // faster checks to see if the live ranges are coalescable. This joiner
1729 // can't swap the LHS/RHS intervals though.
1730 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1731 return SimpleJoin(LHS, RHS);
1733 RHSValNoInfo = RHSValNoInfo0;
1736 // It was defined as a copy from the LHS, find out what value # it is.
1737 RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
1738 RHSValID = RHSValNoInfo->id;
1739 RHSVal0DefinedFromLHS = RHSValID;
1742 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1743 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1744 NewVNInfo.resize(LHS.getNumValNums(), NULL);
1746 // Okay, *all* of the values in LHS that are defined as a copy from RHS
1747 // should now get updated.
1748 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1751 unsigned VN = VNI->id;
1752 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1753 if (LHSSrcReg != RHS.reg) {
1754 // If this is not a copy from the RHS, its value number will be
1755 // unmodified by the coalescing.
1756 NewVNInfo[VN] = VNI;
1757 LHSValNoAssignments[VN] = VN;
1758 } else if (RHSValID == -1) {
1759 // Otherwise, it is a copy from the RHS, and we don't already have a
1760 // value# for it. Keep the current value number, but remember it.
1761 LHSValNoAssignments[VN] = RHSValID = VN;
1762 NewVNInfo[VN] = RHSValNoInfo;
1763 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1765 // Otherwise, use the specified value #.
1766 LHSValNoAssignments[VN] = RHSValID;
1767 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
1768 NewVNInfo[VN] = RHSValNoInfo;
1769 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1773 NewVNInfo[VN] = VNI;
1774 LHSValNoAssignments[VN] = VN;
1778 assert(RHSValID != -1 && "Didn't find value #?");
1779 RHSValNoAssignments[0] = RHSValID;
1780 if (RHSVal0DefinedFromLHS != -1) {
1781 // This path doesn't go through ComputeUltimateVN so just set
1783 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
1786 // Loop over the value numbers of the LHS, seeing if any are defined from
1788 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1791 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
1794 // DstReg is known to be a register in the LHS interval. If the src is
1795 // from the RHS interval, we can use its value #.
1796 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
1799 // Figure out the value # from the RHS.
1800 LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
1803 // Loop over the value numbers of the RHS, seeing if any are defined from
1805 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1808 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
1811 // DstReg is known to be a register in the RHS interval. If the src is
1812 // from the LHS interval, we can use its value #.
1813 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
1816 // Figure out the value # from the LHS.
1817 RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
1820 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1821 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1822 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1824 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1827 unsigned VN = VNI->id;
1828 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1830 ComputeUltimateVN(VNI, NewVNInfo,
1831 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1832 LHSValNoAssignments, RHSValNoAssignments);
1834 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1837 unsigned VN = VNI->id;
1838 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1840 // If this value number isn't a copy from the LHS, it's a new number.
1841 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1842 NewVNInfo.push_back(VNI);
1843 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1847 ComputeUltimateVN(VNI, NewVNInfo,
1848 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1849 RHSValNoAssignments, LHSValNoAssignments);
1853 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1854 // interval lists to see if these intervals are coalescable.
1855 LiveInterval::const_iterator I = LHS.begin();
1856 LiveInterval::const_iterator IE = LHS.end();
1857 LiveInterval::const_iterator J = RHS.begin();
1858 LiveInterval::const_iterator JE = RHS.end();
1860 // Skip ahead until the first place of potential sharing.
1861 if (I->start < J->start) {
1862 I = std::upper_bound(I, IE, J->start);
1863 if (I != LHS.begin()) --I;
1864 } else if (J->start < I->start) {
1865 J = std::upper_bound(J, JE, I->start);
1866 if (J != RHS.begin()) --J;
1870 // Determine if these two live ranges overlap.
1872 if (I->start < J->start) {
1873 Overlaps = I->end > J->start;
1875 Overlaps = J->end > I->start;
1878 // If so, check value # info to determine if they are really different.
1880 // If the live range overlap will map to the same value number in the
1881 // result liverange, we can still coalesce them. If not, we can't.
1882 if (LHSValNoAssignments[I->valno->id] !=
1883 RHSValNoAssignments[J->valno->id])
1887 if (I->end < J->end) {
1896 // Update kill info. Some live ranges are extended due to copy coalescing.
1897 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1898 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1899 VNInfo *VNI = I->first;
1900 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1901 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
1902 NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
1903 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
1906 // Update kill info. Some live ranges are extended due to copy coalescing.
1907 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1908 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1909 VNInfo *VNI = I->first;
1910 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1911 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
1912 NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
1913 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
1916 // If we get here, we know that we can coalesce the live ranges. Ask the
1917 // intervals to coalesce themselves now.
1918 if ((RHS.ranges.size() > LHS.ranges.size() &&
1919 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
1920 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1921 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
1924 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
1931 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1932 // depth of the basic block (the unsigned), and then on the MBB number.
1933 struct DepthMBBCompare {
1934 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1935 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1936 if (LHS.first > RHS.first) return true; // Deeper loops first
1937 return LHS.first == RHS.first &&
1938 LHS.second->getNumber() < RHS.second->getNumber();
1943 /// getRepIntervalSize - Returns the size of the interval that represents the
1944 /// specified register.
1946 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
1947 return Rc->getRepIntervalSize(Reg);
1950 /// CopyRecSort::operator - Join priority queue sorting function.
1952 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
1953 // Inner loops first.
1954 if (left.LoopDepth > right.LoopDepth)
1956 else if (left.LoopDepth == right.LoopDepth)
1957 if (left.isBackEdge && !right.isBackEdge)
1962 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1963 std::vector<CopyRec> &TryAgain) {
1964 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
1966 std::vector<CopyRec> VirtCopies;
1967 std::vector<CopyRec> PhysCopies;
1968 std::vector<CopyRec> ImpDefCopies;
1969 unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
1970 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1972 MachineInstr *Inst = MII++;
1974 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1975 unsigned SrcReg, DstReg;
1976 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1977 DstReg = Inst->getOperand(0).getReg();
1978 SrcReg = Inst->getOperand(1).getReg();
1979 } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
1980 DstReg = Inst->getOperand(0).getReg();
1981 SrcReg = Inst->getOperand(2).getReg();
1982 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
1985 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1986 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1988 JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
1990 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1991 ImpDefCopies.push_back(CopyRec(Inst, 0, false));
1992 else if (SrcIsPhys || DstIsPhys)
1993 PhysCopies.push_back(CopyRec(Inst, 0, false));
1995 VirtCopies.push_back(CopyRec(Inst, 0, false));
2002 // Try coalescing implicit copies first, followed by copies to / from
2003 // physical registers, then finally copies from virtual registers to
2004 // virtual registers.
2005 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
2006 CopyRec &TheCopy = ImpDefCopies[i];
2008 if (!JoinCopy(TheCopy, Again))
2010 TryAgain.push_back(TheCopy);
2012 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
2013 CopyRec &TheCopy = PhysCopies[i];
2015 if (!JoinCopy(TheCopy, Again))
2017 TryAgain.push_back(TheCopy);
2019 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
2020 CopyRec &TheCopy = VirtCopies[i];
2022 if (!JoinCopy(TheCopy, Again))
2024 TryAgain.push_back(TheCopy);
2028 void SimpleRegisterCoalescing::joinIntervals() {
2029 DOUT << "********** JOINING INTERVALS ***********\n";
2032 JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
2034 std::vector<CopyRec> TryAgainList;
2035 if (loopInfo->empty()) {
2036 // If there are no loops in the function, join intervals in function order.
2037 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
2039 CopyCoalesceInMBB(I, TryAgainList);
2041 // Otherwise, join intervals in inner loops before other intervals.
2042 // Unfortunately we can't just iterate over loop hierarchy here because
2043 // there may be more MBB's than BB's. Collect MBB's for sorting.
2045 // Join intervals in the function prolog first. We want to join physical
2046 // registers with virtual registers before the intervals got too long.
2047 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
2048 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
2049 MachineBasicBlock *MBB = I;
2050 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
2053 // Sort by loop depth.
2054 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2056 // Finally, join intervals in loop nest order.
2057 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2058 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
2061 // Joining intervals can allow other intervals to be joined. Iteratively join
2062 // until we make no progress.
2064 SmallVector<CopyRec, 16> TryAgain;
2065 bool ProgressMade = true;
2066 while (ProgressMade) {
2067 ProgressMade = false;
2068 while (!JoinQueue->empty()) {
2069 CopyRec R = JoinQueue->pop();
2071 bool Success = JoinCopy(R, Again);
2073 ProgressMade = true;
2075 TryAgain.push_back(R);
2079 while (!TryAgain.empty()) {
2080 JoinQueue->push(TryAgain.back());
2081 TryAgain.pop_back();
2086 bool ProgressMade = true;
2087 while (ProgressMade) {
2088 ProgressMade = false;
2090 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
2091 CopyRec &TheCopy = TryAgainList[i];
2094 bool Success = JoinCopy(TheCopy, Again);
2095 if (Success || !Again) {
2096 TheCopy.MI = 0; // Mark this one as done.
2097 ProgressMade = true;
2108 /// Return true if the two specified registers belong to different register
2109 /// classes. The registers may be either phys or virt regs. In the
2110 /// case where both registers are virtual registers, it would also returns
2111 /// true by reference the RegB register class in SubRC if it is a subset of
2112 /// RegA's register class.
2114 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA, unsigned RegB,
2115 const TargetRegisterClass *&SubRC) const {
2117 // Get the register classes for the first reg.
2118 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
2119 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
2120 "Shouldn't consider two physregs!");
2121 return !mri_->getRegClass(RegB)->contains(RegA);
2124 // Compare against the regclass for the second reg.
2125 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
2126 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
2127 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
2128 if (RegClassA == RegClassB)
2130 SubRC = (RegClassA->hasSubClass(RegClassB)) ? RegClassB : NULL;
2133 return !RegClassA->contains(RegB);
2136 /// lastRegisterUse - Returns the last use of the specific register between
2137 /// cycles Start and End or NULL if there are no uses.
2139 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
2140 unsigned Reg, unsigned &UseIdx) const{
2142 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2143 MachineOperand *LastUse = NULL;
2144 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
2145 E = mri_->use_end(); I != E; ++I) {
2146 MachineOperand &Use = I.getOperand();
2147 MachineInstr *UseMI = Use.getParent();
2148 unsigned SrcReg, DstReg;
2149 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg) && SrcReg == DstReg)
2150 // Ignore identity copies.
2152 unsigned Idx = li_->getInstructionIndex(UseMI);
2153 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
2161 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
2164 // Skip deleted instructions
2165 MachineInstr *MI = li_->getInstructionFromIndex(e);
2166 while ((e - InstrSlots::NUM) >= s && !MI) {
2167 e -= InstrSlots::NUM;
2168 MI = li_->getInstructionFromIndex(e);
2170 if (e < s || MI == NULL)
2173 // Ignore identity copies.
2174 unsigned SrcReg, DstReg;
2175 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg))
2176 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2177 MachineOperand &Use = MI->getOperand(i);
2178 if (Use.isReg() && Use.isUse() && Use.getReg() &&
2179 tri_->regsOverlap(Use.getReg(), Reg)) {
2185 e -= InstrSlots::NUM;
2192 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
2193 if (TargetRegisterInfo::isPhysicalRegister(reg))
2194 cerr << tri_->getName(reg);
2196 cerr << "%reg" << reg;
2199 void SimpleRegisterCoalescing::releaseMemory() {
2200 JoinedCopies.clear();
2201 ReMatCopies.clear();
2205 static bool isZeroLengthInterval(LiveInterval *li) {
2206 for (LiveInterval::Ranges::const_iterator
2207 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
2208 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
2213 /// TurnCopyIntoImpDef - If source of the specified copy is an implicit def,
2214 /// turn the copy into an implicit def.
2216 SimpleRegisterCoalescing::TurnCopyIntoImpDef(MachineBasicBlock::iterator &I,
2217 MachineBasicBlock *MBB,
2218 unsigned DstReg, unsigned SrcReg) {
2219 MachineInstr *CopyMI = &*I;
2220 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
2221 if (!li_->hasInterval(SrcReg))
2223 LiveInterval &SrcInt = li_->getInterval(SrcReg);
2224 if (!SrcInt.empty())
2226 if (!li_->hasInterval(DstReg))
2228 LiveInterval &DstInt = li_->getInterval(DstReg);
2229 const LiveRange *DstLR = DstInt.getLiveRangeContaining(CopyIdx);
2230 DstInt.removeValNo(DstLR->valno);
2231 CopyMI->setDesc(tii_->get(TargetInstrInfo::IMPLICIT_DEF));
2232 for (int i = CopyMI->getNumOperands() - 1, e = 0; i > e; --i)
2233 CopyMI->RemoveOperand(i);
2234 bool NoUse = mri_->use_empty(SrcReg);
2236 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
2237 E = mri_->reg_end(); I != E; ) {
2238 assert(I.getOperand().isDef());
2239 MachineInstr *DefMI = &*I;
2241 // The implicit_def source has no other uses, delete it.
2242 assert(DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF);
2243 li_->RemoveMachineInstrFromMaps(DefMI);
2244 DefMI->eraseFromParent();
2252 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2254 mri_ = &fn.getRegInfo();
2255 tm_ = &fn.getTarget();
2256 tri_ = tm_->getRegisterInfo();
2257 tii_ = tm_->getInstrInfo();
2258 li_ = &getAnalysis<LiveIntervals>();
2259 loopInfo = &getAnalysis<MachineLoopInfo>();
2261 DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
2262 << "********** Function: "
2263 << ((Value*)mf_->getFunction())->getName() << '\n';
2265 allocatableRegs_ = tri_->getAllocatableSet(fn);
2266 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2267 E = tri_->regclass_end(); I != E; ++I)
2268 allocatableRCRegs_.insert(std::make_pair(*I,
2269 tri_->getAllocatableSet(fn, *I)));
2271 // Join (coalesce) intervals if requested.
2272 if (EnableJoining) {
2274 DOUT << "********** INTERVALS POST JOINING **********\n";
2275 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
2276 I->second->print(DOUT, tri_);
2281 // Perform a final pass over the instructions and compute spill weights
2282 // and remove identity moves.
2283 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2284 mbbi != mbbe; ++mbbi) {
2285 MachineBasicBlock* mbb = mbbi;
2286 unsigned loopDepth = loopInfo->getLoopDepth(mbb);
2288 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2290 MachineInstr *MI = mii;
2291 unsigned SrcReg, DstReg;
2292 if (JoinedCopies.count(MI)) {
2293 // Delete all coalesced copies.
2294 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg)) {
2295 assert((MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
2296 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) &&
2297 "Unrecognized copy instruction");
2298 DstReg = MI->getOperand(0).getReg();
2300 if (MI->registerDefIsDead(DstReg)) {
2301 LiveInterval &li = li_->getInterval(DstReg);
2302 if (!ShortenDeadCopySrcLiveRange(li, MI))
2303 ShortenDeadCopyLiveRange(li, MI);
2305 li_->RemoveMachineInstrFromMaps(MI);
2306 mii = mbbi->erase(mii);
2311 // Now check if this is a remat'ed def instruction which is now dead.
2312 if (ReMatDefs.count(MI)) {
2314 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2315 const MachineOperand &MO = MI->getOperand(i);
2316 if (!MO.isReg() || MO.isDead())
2318 unsigned Reg = MO.getReg();
2319 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
2320 !mri_->use_empty(Reg)) {
2326 li_->RemoveMachineInstrFromMaps(mii);
2327 mii = mbbi->erase(mii);
2332 // If the move will be an identity move delete it
2333 bool isMove = tii_->isMoveInstr(*MI, SrcReg, DstReg);
2334 if (isMove && SrcReg == DstReg) {
2335 if (li_->hasInterval(SrcReg)) {
2336 LiveInterval &RegInt = li_->getInterval(SrcReg);
2337 // If def of this move instruction is dead, remove its live range
2338 // from the dstination register's live interval.
2339 if (MI->registerDefIsDead(DstReg)) {
2340 if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
2341 ShortenDeadCopyLiveRange(RegInt, MI);
2344 li_->RemoveMachineInstrFromMaps(MI);
2345 mii = mbbi->erase(mii);
2347 } else if (!isMove || !TurnCopyIntoImpDef(mii, mbb, DstReg, SrcReg)) {
2348 SmallSet<unsigned, 4> UniqueUses;
2349 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2350 const MachineOperand &mop = MI->getOperand(i);
2351 if (mop.isReg() && mop.getReg() &&
2352 TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
2353 unsigned reg = mop.getReg();
2354 // Multiple uses of reg by the same instruction. It should not
2355 // contribute to spill weight again.
2356 if (UniqueUses.count(reg) != 0)
2358 LiveInterval &RegInt = li_->getInterval(reg);
2360 li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
2361 UniqueUses.insert(reg);
2369 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
2370 LiveInterval &LI = *I->second;
2371 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
2372 // If the live interval length is essentially zero, i.e. in every live
2373 // range the use follows def immediately, it doesn't make sense to spill
2374 // it and hope it will be easier to allocate for this li.
2375 if (isZeroLengthInterval(&LI))
2376 LI.weight = HUGE_VALF;
2378 bool isLoad = false;
2379 SmallVector<LiveInterval*, 4> SpillIs;
2380 if (li_->isReMaterializable(LI, SpillIs, isLoad)) {
2381 // If all of the definitions of the interval are re-materializable,
2382 // it is a preferred candidate for spilling. If non of the defs are
2383 // loads, then it's potentially very cheap to re-materialize.
2384 // FIXME: this gets much more complicated once we support non-trivial
2385 // re-materialization.
2393 // Slightly prefer live interval that has been assigned a preferred reg.
2397 // Divide the weight of the interval by its size. This encourages
2398 // spilling of intervals that are large and have few uses, and
2399 // discourages spilling of small intervals with many uses.
2400 LI.weight /= li_->getApproximateInstructionCount(LI) * InstrSlots::NUM;
2408 /// print - Implement the dump method.
2409 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
2413 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2414 return new SimpleRegisterCoalescing();
2417 // Make sure that anything that uses RegisterCoalescer pulls in this file...
2418 DEFINING_FILE_FOR(SimpleRegisterCoalescing)