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 "LiveDebugVariables.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/Value.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/CodeGen/RegisterCoalescer.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/ADT/OwningPtr.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/ADT/STLExtras.h"
43 STATISTIC(numJoins , "Number of interval joins performed");
44 STATISTIC(numCrossRCs , "Number of cross class joins performed");
45 STATISTIC(numCommutes , "Number of instruction commuting performed");
46 STATISTIC(numExtends , "Number of copies extended");
47 STATISTIC(NumReMats , "Number of instructions re-materialized");
48 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
49 STATISTIC(numAborts , "Number of times interval joining aborted");
51 char SimpleRegisterCoalescing::ID = 0;
53 EnableJoining("join-liveintervals",
54 cl::desc("Coalesce copies (default=true)"),
58 DisableCrossClassJoin("disable-cross-class-join",
59 cl::desc("Avoid coalescing cross register class copies"),
60 cl::init(false), cl::Hidden);
63 EnablePhysicalJoin("join-physregs",
64 cl::desc("Join physical register copies"),
65 cl::init(false), cl::Hidden);
68 VerifyCoalescing("verify-coalescing",
69 cl::desc("Verify machine instrs before and after register coalescing"),
72 INITIALIZE_AG_PASS_BEGIN(SimpleRegisterCoalescing, RegisterCoalescer,
73 "simple-register-coalescing", "Simple Register Coalescing",
75 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
76 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
77 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
78 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
79 INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination)
80 INITIALIZE_PASS_DEPENDENCY(PHIElimination)
81 INITIALIZE_PASS_DEPENDENCY(TwoAddressInstructionPass)
82 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
83 INITIALIZE_AG_PASS_END(SimpleRegisterCoalescing, RegisterCoalescer,
84 "simple-register-coalescing", "Simple Register Coalescing",
87 char &llvm::SimpleRegisterCoalescingID = SimpleRegisterCoalescing::ID;
89 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
91 AU.addRequired<AliasAnalysis>();
92 AU.addRequired<LiveIntervals>();
93 AU.addPreserved<LiveIntervals>();
94 AU.addRequired<LiveDebugVariables>();
95 AU.addPreserved<LiveDebugVariables>();
96 AU.addPreserved<SlotIndexes>();
97 AU.addRequired<MachineLoopInfo>();
98 AU.addPreserved<MachineLoopInfo>();
99 AU.addPreservedID(MachineDominatorsID);
100 AU.addPreservedID(StrongPHIEliminationID);
101 AU.addPreservedID(PHIEliminationID);
102 AU.addPreservedID(TwoAddressInstructionPassID);
103 MachineFunctionPass::getAnalysisUsage(AU);
106 void SimpleRegisterCoalescing::markAsJoined(MachineInstr *CopyMI) {
107 /// Joined copies are not deleted immediately, but kept in JoinedCopies.
108 JoinedCopies.insert(CopyMI);
110 /// Mark all register operands of CopyMI as <undef> so they won't affect dead
111 /// code elimination.
112 for (MachineInstr::mop_iterator I = CopyMI->operands_begin(),
113 E = CopyMI->operands_end(); I != E; ++I)
118 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
119 /// being the source and IntB being the dest, thus this defines a value number
120 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
121 /// see if we can merge these two pieces of B into a single value number,
122 /// eliminating a copy. For example:
126 /// B1 = A3 <- this copy
128 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
129 /// value number to be replaced with B0 (which simplifies the B liveinterval).
131 /// This returns true if an interval was modified.
133 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(const CoalescerPair &CP,
134 MachineInstr *CopyMI) {
135 // Bail if there is no dst interval - can happen when merging physical subreg
137 if (!li_->hasInterval(CP.getDstReg()))
141 li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
143 li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
144 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
146 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
147 // the example above.
148 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
149 if (BLR == IntB.end()) return false;
150 VNInfo *BValNo = BLR->valno;
152 // Get the location that B is defined at. Two options: either this value has
153 // an unknown definition point or it is defined at CopyIdx. If unknown, we
155 if (!BValNo->isDefByCopy()) return false;
156 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
158 // AValNo is the value number in A that defines the copy, A3 in the example.
159 SlotIndex CopyUseIdx = CopyIdx.getUseIndex();
160 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
161 // The live range might not exist after fun with physreg coalescing.
162 if (ALR == IntA.end()) return false;
163 VNInfo *AValNo = ALR->valno;
164 // If it's re-defined by an early clobber somewhere in the live range, then
165 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
167 // 172 %ECX<def> = MOV32rr %reg1039<kill>
168 // 180 INLINEASM <es:subl $5,$1
169 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9,
171 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
172 // 188 %EAX<def> = MOV32rr %EAX<kill>
173 // 196 %ECX<def> = MOV32rr %ECX<kill>
174 // 204 %ECX<def> = MOV32rr %ECX<kill>
175 // 212 %EAX<def> = MOV32rr %EAX<kill>
176 // 220 %EAX<def> = MOV32rr %EAX
177 // 228 %reg1039<def> = MOV32rr %ECX<kill>
178 // The early clobber operand ties ECX input to the ECX def.
180 // The live interval of ECX is represented as this:
181 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
182 // The coalescer has no idea there was a def in the middle of [174,230].
183 if (AValNo->hasRedefByEC())
186 // If AValNo is defined as a copy from IntB, we can potentially process this.
187 // Get the instruction that defines this value number.
188 if (!CP.isCoalescable(AValNo->getCopy()))
191 // Get the LiveRange in IntB that this value number starts with.
192 LiveInterval::iterator ValLR =
193 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
194 if (ValLR == IntB.end())
197 // Make sure that the end of the live range is inside the same block as
199 MachineInstr *ValLREndInst =
200 li_->getInstructionFromIndex(ValLR->end.getPrevSlot());
201 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
204 // Okay, we now know that ValLR ends in the same block that the CopyMI
205 // live-range starts. If there are no intervening live ranges between them in
206 // IntB, we can merge them.
207 if (ValLR+1 != BLR) return false;
209 // If a live interval is a physical register, conservatively check if any
210 // of its aliases is overlapping the live interval of the virtual register.
211 // If so, do not coalesce.
212 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
213 for (const unsigned *AS = tri_->getAliasSet(IntB.reg); *AS; ++AS)
214 if (li_->hasInterval(*AS) && IntA.overlaps(li_->getInterval(*AS))) {
216 dbgs() << "\t\tInterfere with alias ";
217 li_->getInterval(*AS).print(dbgs(), tri_);
224 dbgs() << "Extending: ";
225 IntB.print(dbgs(), tri_);
228 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
229 // We are about to delete CopyMI, so need to remove it as the 'instruction
230 // that defines this value #'. Update the valnum with the new defining
232 BValNo->def = FillerStart;
235 // Okay, we can merge them. We need to insert a new liverange:
236 // [ValLR.end, BLR.begin) of either value number, then we merge the
237 // two value numbers.
238 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
240 // If the IntB live range is assigned to a physical register, and if that
241 // physreg has sub-registers, update their live intervals as well.
242 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
243 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
244 if (!li_->hasInterval(*SR))
246 LiveInterval &SRLI = li_->getInterval(*SR);
247 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
248 SRLI.getNextValue(FillerStart, 0,
249 li_->getVNInfoAllocator())));
253 // Okay, merge "B1" into the same value number as "B0".
254 if (BValNo != ValLR->valno) {
255 // If B1 is killed by a PHI, then the merged live range must also be killed
256 // by the same PHI, as B0 and B1 can not overlap.
257 bool HasPHIKill = BValNo->hasPHIKill();
258 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
260 ValLR->valno->setHasPHIKill(true);
263 dbgs() << " result = ";
264 IntB.print(dbgs(), tri_);
268 // If the source instruction was killing the source register before the
269 // merge, unset the isKill marker given the live range has been extended.
270 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
272 ValLREndInst->getOperand(UIdx).setIsKill(false);
275 // If the copy instruction was killing the destination register before the
276 // merge, find the last use and trim the live range. That will also add the
278 if (ALR->end == CopyIdx)
279 li_->shrinkToUses(&IntA);
285 /// HasOtherReachingDefs - Return true if there are definitions of IntB
286 /// other than BValNo val# that can reach uses of AValno val# of IntA.
287 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
291 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
293 if (AI->valno != AValNo) continue;
294 LiveInterval::Ranges::iterator BI =
295 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
296 if (BI != IntB.ranges.begin())
298 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
299 if (BI->valno == BValNo)
301 if (BI->start <= AI->start && BI->end > AI->start)
303 if (BI->start > AI->start && BI->start < AI->end)
310 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
311 /// IntA being the source and IntB being the dest, thus this defines a value
312 /// number in IntB. If the source value number (in IntA) is defined by a
313 /// commutable instruction and its other operand is coalesced to the copy dest
314 /// register, see if we can transform the copy into a noop by commuting the
315 /// definition. For example,
317 /// A3 = op A2 B0<kill>
319 /// B1 = A3 <- this copy
321 /// = op A3 <- more uses
325 /// B2 = op B0 A2<kill>
327 /// B1 = B2 <- now an identify copy
329 /// = op B2 <- more uses
331 /// This returns true if an interval was modified.
333 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(const CoalescerPair &CP,
334 MachineInstr *CopyMI) {
335 // FIXME: For now, only eliminate the copy by commuting its def when the
336 // source register is a virtual register. We want to guard against cases
337 // where the copy is a back edge copy and commuting the def lengthen the
338 // live interval of the source register to the entire loop.
339 if (CP.isPhys() && CP.isFlipped())
342 // Bail if there is no dst interval.
343 if (!li_->hasInterval(CP.getDstReg()))
346 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
349 li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
351 li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
353 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
354 // the example above.
355 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
356 if (!BValNo || !BValNo->isDefByCopy())
359 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
361 // AValNo is the value number in A that defines the copy, A3 in the example.
362 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getUseIndex());
363 assert(AValNo && "COPY source not live");
365 // If other defs can reach uses of this def, then it's not safe to perform
367 if (AValNo->isPHIDef() || AValNo->isUnused() || AValNo->hasPHIKill())
369 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
372 const TargetInstrDesc &TID = DefMI->getDesc();
373 if (!TID.isCommutable())
375 // If DefMI is a two-address instruction then commuting it will change the
376 // destination register.
377 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
378 assert(DefIdx != -1);
380 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
382 unsigned Op1, Op2, NewDstIdx;
383 if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
387 else if (Op2 == UseOpIdx)
392 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
393 unsigned NewReg = NewDstMO.getReg();
394 if (NewReg != IntB.reg || !NewDstMO.isKill())
397 // Make sure there are no other definitions of IntB that would reach the
398 // uses which the new definition can reach.
399 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
402 // Abort if the aliases of IntB.reg have values that are not simply the
403 // clobbers from the superreg.
404 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
405 for (const unsigned *AS = tri_->getAliasSet(IntB.reg); *AS; ++AS)
406 if (li_->hasInterval(*AS) &&
407 HasOtherReachingDefs(IntA, li_->getInterval(*AS), AValNo, 0))
410 // If some of the uses of IntA.reg is already coalesced away, return false.
411 // It's not possible to determine whether it's safe to perform the coalescing.
412 for (MachineRegisterInfo::use_nodbg_iterator UI =
413 mri_->use_nodbg_begin(IntA.reg),
414 UE = mri_->use_nodbg_end(); UI != UE; ++UI) {
415 MachineInstr *UseMI = &*UI;
416 SlotIndex UseIdx = li_->getInstructionIndex(UseMI);
417 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
418 if (ULR == IntA.end())
420 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
424 DEBUG(dbgs() << "\tRemoveCopyByCommutingDef: " << AValNo->def << '\t'
427 // At this point we have decided that it is legal to do this
428 // transformation. Start by commuting the instruction.
429 MachineBasicBlock *MBB = DefMI->getParent();
430 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
433 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
434 TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
435 !mri_->constrainRegClass(IntB.reg, mri_->getRegClass(IntA.reg)))
437 if (NewMI != DefMI) {
438 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
439 MBB->insert(DefMI, NewMI);
442 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
443 NewMI->getOperand(OpIdx).setIsKill();
445 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
454 // Update uses of IntA of the specific Val# with IntB.
455 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
456 UE = mri_->use_end(); UI != UE;) {
457 MachineOperand &UseMO = UI.getOperand();
458 MachineInstr *UseMI = &*UI;
460 if (JoinedCopies.count(UseMI))
462 if (UseMI->isDebugValue()) {
463 // FIXME These don't have an instruction index. Not clear we have enough
464 // info to decide whether to do this replacement or not. For now do it.
465 UseMO.setReg(NewReg);
468 SlotIndex UseIdx = li_->getInstructionIndex(UseMI).getUseIndex();
469 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
470 if (ULR == IntA.end() || ULR->valno != AValNo)
472 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
473 UseMO.substPhysReg(NewReg, *tri_);
475 UseMO.setReg(NewReg);
478 if (!UseMI->isCopy())
480 if (UseMI->getOperand(0).getReg() != IntB.reg ||
481 UseMI->getOperand(0).getSubReg())
484 // This copy will become a noop. If it's defining a new val#, merge it into
486 SlotIndex DefIdx = UseIdx.getDefIndex();
487 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
490 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
491 assert(DVNI->def == DefIdx);
492 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
496 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
498 VNInfo *ValNo = BValNo;
499 ValNo->def = AValNo->def;
501 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
503 if (AI->valno != AValNo) continue;
504 IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
506 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
508 IntA.removeValNo(AValNo);
509 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
514 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
515 /// computation, replace the copy by rematerialize the definition.
516 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
520 MachineInstr *CopyMI) {
521 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getUseIndex();
522 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
523 assert(SrcLR != SrcInt.end() && "Live range not found!");
524 VNInfo *ValNo = SrcLR->valno;
525 // If other defs can reach uses of this def, then it's not safe to perform
527 if (ValNo->isPHIDef() || ValNo->isUnused() || ValNo->hasPHIKill())
529 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
532 assert(DefMI && "Defining instruction disappeared");
533 const TargetInstrDesc &TID = DefMI->getDesc();
534 if (!TID.isAsCheapAsAMove())
536 if (!tii_->isTriviallyReMaterializable(DefMI, AA))
538 bool SawStore = false;
539 if (!DefMI->isSafeToMove(tii_, AA, SawStore))
541 if (TID.getNumDefs() != 1)
543 if (!DefMI->isImplicitDef()) {
544 // Make sure the copy destination register class fits the instruction
545 // definition register class. The mismatch can happen as a result of earlier
546 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
547 const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
548 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
549 if (mri_->getRegClass(DstReg) != RC)
551 } else if (!RC->contains(DstReg))
555 // If destination register has a sub-register index on it, make sure it
556 // matches the instruction register class.
558 const TargetInstrDesc &TID = DefMI->getDesc();
559 if (TID.getNumDefs() != 1)
561 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
562 const TargetRegisterClass *DstSubRC =
563 DstRC->getSubRegisterRegClass(DstSubIdx);
564 const TargetRegisterClass *DefRC = TID.OpInfo[0].getRegClass(tri_);
567 else if (DefRC != DstSubRC)
571 RemoveCopyFlag(DstReg, CopyMI);
573 MachineBasicBlock *MBB = CopyMI->getParent();
574 MachineBasicBlock::iterator MII =
575 llvm::next(MachineBasicBlock::iterator(CopyMI));
576 tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI, *tri_);
577 MachineInstr *NewMI = prior(MII);
579 // CopyMI may have implicit operands, transfer them over to the newly
580 // rematerialized instruction. And update implicit def interval valnos.
581 for (unsigned i = CopyMI->getDesc().getNumOperands(),
582 e = CopyMI->getNumOperands(); i != e; ++i) {
583 MachineOperand &MO = CopyMI->getOperand(i);
584 if (MO.isReg() && MO.isImplicit())
585 NewMI->addOperand(MO);
587 RemoveCopyFlag(MO.getReg(), CopyMI);
590 NewMI->copyImplicitOps(CopyMI);
591 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
592 CopyMI->eraseFromParent();
593 ReMatCopies.insert(CopyMI);
594 ReMatDefs.insert(DefMI);
595 DEBUG(dbgs() << "Remat: " << *NewMI);
598 // The source interval can become smaller because we removed a use.
600 li_->shrinkToUses(&SrcInt);
605 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
606 /// update the subregister number if it is not zero. If DstReg is a
607 /// physical register and the existing subregister number of the def / use
608 /// being updated is not zero, make sure to set it to the correct physical
611 SimpleRegisterCoalescing::UpdateRegDefsUses(const CoalescerPair &CP) {
612 bool DstIsPhys = CP.isPhys();
613 unsigned SrcReg = CP.getSrcReg();
614 unsigned DstReg = CP.getDstReg();
615 unsigned SubIdx = CP.getSubIdx();
617 // Update LiveDebugVariables.
618 ldv_->renameRegister(SrcReg, DstReg, SubIdx);
620 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg);
621 MachineInstr *UseMI = I.skipInstruction();) {
622 // A PhysReg copy that won't be coalesced can perhaps be rematerialized
625 if (UseMI->isCopy() &&
626 !UseMI->getOperand(1).getSubReg() &&
627 !UseMI->getOperand(0).getSubReg() &&
628 UseMI->getOperand(1).getReg() == SrcReg &&
629 UseMI->getOperand(0).getReg() != SrcReg &&
630 UseMI->getOperand(0).getReg() != DstReg &&
631 !JoinedCopies.count(UseMI) &&
632 ReMaterializeTrivialDef(li_->getInterval(SrcReg), false,
633 UseMI->getOperand(0).getReg(), 0, UseMI))
637 SmallVector<unsigned,8> Ops;
639 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
640 bool Kills = false, Deads = false;
642 // Replace SrcReg with DstReg in all UseMI operands.
643 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
644 MachineOperand &MO = UseMI->getOperand(Ops[i]);
645 Kills |= MO.isKill();
646 Deads |= MO.isDead();
649 MO.substPhysReg(DstReg, *tri_);
651 MO.substVirtReg(DstReg, SubIdx, *tri_);
654 // This instruction is a copy that will be removed.
655 if (JoinedCopies.count(UseMI))
659 // If UseMI was a simple SrcReg def, make sure we didn't turn it into a
660 // read-modify-write of DstReg.
662 UseMI->addRegisterDead(DstReg, tri_);
663 else if (!Reads && Writes)
664 UseMI->addRegisterDefined(DstReg, tri_);
666 // Kill flags apply to the whole physical register.
667 if (DstIsPhys && Kills)
668 UseMI->addRegisterKilled(DstReg, tri_);
672 dbgs() << "\t\tupdated: ";
673 if (!UseMI->isDebugValue())
674 dbgs() << li_->getInstructionIndex(UseMI) << "\t";
680 /// removeIntervalIfEmpty - Check if the live interval of a physical register
681 /// is empty, if so remove it and also remove the empty intervals of its
682 /// sub-registers. Return true if live interval is removed.
683 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
684 const TargetRegisterInfo *tri_) {
686 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
687 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
688 if (!li_->hasInterval(*SR))
690 LiveInterval &sli = li_->getInterval(*SR);
692 li_->removeInterval(*SR);
694 li_->removeInterval(li.reg);
700 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
701 /// the val# it defines. If the live interval becomes empty, remove it as well.
702 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
703 MachineInstr *DefMI) {
704 SlotIndex DefIdx = li_->getInstructionIndex(DefMI).getDefIndex();
705 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
706 if (DefIdx != MLR->valno->def)
708 li.removeValNo(MLR->valno);
709 return removeIntervalIfEmpty(li, li_, tri_);
712 void SimpleRegisterCoalescing::RemoveCopyFlag(unsigned DstReg,
713 const MachineInstr *CopyMI) {
714 SlotIndex DefIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
715 if (li_->hasInterval(DstReg)) {
716 LiveInterval &LI = li_->getInterval(DstReg);
717 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
718 if (LR->valno->def == DefIdx)
719 LR->valno->setCopy(0);
721 if (!TargetRegisterInfo::isPhysicalRegister(DstReg))
723 for (const unsigned* AS = tri_->getAliasSet(DstReg); *AS; ++AS) {
724 if (!li_->hasInterval(*AS))
726 LiveInterval &LI = li_->getInterval(*AS);
727 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
728 if (LR->valno->def == DefIdx)
729 LR->valno->setCopy(0);
733 /// shouldJoinPhys - Return true if a copy involving a physreg should be joined.
734 /// We need to be careful about coalescing a source physical register with a
735 /// virtual register. Once the coalescing is done, it cannot be broken and these
736 /// are not spillable! If the destination interval uses are far away, think
737 /// twice about coalescing them!
738 bool SimpleRegisterCoalescing::shouldJoinPhys(CoalescerPair &CP) {
739 bool Allocatable = li_->isAllocatable(CP.getDstReg());
740 LiveInterval &JoinVInt = li_->getInterval(CP.getSrcReg());
742 /// Always join simple intervals that are defined by a single copy from a
743 /// reserved register. This doesn't increase register pressure, so it is
744 /// always beneficial.
745 if (!Allocatable && CP.isFlipped() && JoinVInt.containsOneValue())
748 if (!EnablePhysicalJoin) {
749 DEBUG(dbgs() << "\tPhysreg joins disabled.\n");
753 // Only coalesce to allocatable physreg, we don't want to risk modifying
754 // reserved registers.
756 DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n");
757 return false; // Not coalescable.
760 // Don't join with physregs that have a ridiculous number of live
761 // ranges. The data structure performance is really bad when that
763 if (li_->hasInterval(CP.getDstReg()) &&
764 li_->getInterval(CP.getDstReg()).ranges.size() > 1000) {
767 << "\tPhysical register live interval too complicated, abort!\n");
771 // FIXME: Why are we skipping this test for partial copies?
772 // CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
773 if (!CP.isPartial()) {
774 const TargetRegisterClass *RC = mri_->getRegClass(CP.getSrcReg());
775 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
776 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
777 if (Length > Threshold) {
779 DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
786 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
787 /// two virtual registers from different register classes.
789 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned SrcReg,
791 const TargetRegisterClass *SrcRC,
792 const TargetRegisterClass *DstRC,
793 const TargetRegisterClass *NewRC) {
794 unsigned NewRCCount = allocatableRCRegs_[NewRC].count();
795 // This heuristics is good enough in practice, but it's obviously not *right*.
796 // 4 is a magic number that works well enough for x86, ARM, etc. It filter
797 // out all but the most restrictive register classes.
798 if (NewRCCount > 4 ||
799 // Early exit if the function is fairly small, coalesce aggressively if
800 // that's the case. For really special register classes with 3 or
801 // fewer registers, be a bit more careful.
802 (li_->getFuncInstructionCount() / NewRCCount) < 8)
804 LiveInterval &SrcInt = li_->getInterval(SrcReg);
805 LiveInterval &DstInt = li_->getInterval(DstReg);
806 unsigned SrcSize = li_->getApproximateInstructionCount(SrcInt);
807 unsigned DstSize = li_->getApproximateInstructionCount(DstInt);
809 // Coalesce aggressively if the intervals are small compared to the number of
810 // registers in the new class. The number 4 is fairly arbitrary, chosen to be
811 // less aggressive than the 8 used for the whole function size.
812 const unsigned ThresSize = 4 * NewRCCount;
813 if (SrcSize <= ThresSize && DstSize <= ThresSize)
816 // Estimate *register use density*. If it doubles or more, abort.
817 unsigned SrcUses = std::distance(mri_->use_nodbg_begin(SrcReg),
818 mri_->use_nodbg_end());
819 unsigned DstUses = std::distance(mri_->use_nodbg_begin(DstReg),
820 mri_->use_nodbg_end());
821 unsigned NewUses = SrcUses + DstUses;
822 unsigned NewSize = SrcSize + DstSize;
823 if (SrcRC != NewRC && SrcSize > ThresSize) {
824 unsigned SrcRCCount = allocatableRCRegs_[SrcRC].count();
825 if (NewUses*SrcSize*SrcRCCount > 2*SrcUses*NewSize*NewRCCount)
828 if (DstRC != NewRC && DstSize > ThresSize) {
829 unsigned DstRCCount = allocatableRCRegs_[DstRC].count();
830 if (NewUses*DstSize*DstRCCount > 2*DstUses*NewSize*NewRCCount)
837 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
838 /// which are the src/dst of the copy instruction CopyMI. This returns true
839 /// if the copy was successfully coalesced away. If it is not currently
840 /// possible to coalesce this interval, but it may be possible if other
841 /// things get coalesced, then it returns true by reference in 'Again'.
842 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
843 MachineInstr *CopyMI = TheCopy.MI;
846 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
847 return false; // Already done.
849 DEBUG(dbgs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
851 CoalescerPair CP(*tii_, *tri_);
852 if (!CP.setRegisters(CopyMI)) {
853 DEBUG(dbgs() << "\tNot coalescable.\n");
857 // If they are already joined we continue.
858 if (CP.getSrcReg() == CP.getDstReg()) {
859 markAsJoined(CopyMI);
860 DEBUG(dbgs() << "\tCopy already coalesced.\n");
861 return false; // Not coalescable.
864 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), tri_)
865 << " with " << PrintReg(CP.getDstReg(), tri_, CP.getSubIdx())
870 if (!shouldJoinPhys(CP)) {
871 // Before giving up coalescing, if definition of source is defined by
872 // trivial computation, try rematerializing it.
873 if (!CP.isFlipped() &&
874 ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()), true,
875 CP.getDstReg(), 0, CopyMI))
880 // Avoid constraining virtual register regclass too much.
881 if (CP.isCrossClass()) {
882 DEBUG(dbgs() << "\tCross-class to " << CP.getNewRC()->getName() << ".\n");
883 if (DisableCrossClassJoin) {
884 DEBUG(dbgs() << "\tCross-class joins disabled.\n");
887 if (!isWinToJoinCrossClass(CP.getSrcReg(), CP.getDstReg(),
888 mri_->getRegClass(CP.getSrcReg()),
889 mri_->getRegClass(CP.getDstReg()),
891 DEBUG(dbgs() << "\tAvoid coalescing to constrained register class.\n");
892 Again = true; // May be possible to coalesce later.
897 // When possible, let DstReg be the larger interval.
898 if (!CP.getSubIdx() && li_->getInterval(CP.getSrcReg()).ranges.size() >
899 li_->getInterval(CP.getDstReg()).ranges.size())
903 // Okay, attempt to join these two intervals. On failure, this returns false.
904 // Otherwise, if one of the intervals being joined is a physreg, this method
905 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
906 // been modified, so we can use this information below to update aliases.
907 if (!JoinIntervals(CP)) {
908 // Coalescing failed.
910 // If definition of source is defined by trivial computation, try
911 // rematerializing it.
912 if (!CP.isFlipped() &&
913 ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()), true,
914 CP.getDstReg(), 0, CopyMI))
917 // If we can eliminate the copy without merging the live ranges, do so now.
918 if (!CP.isPartial()) {
919 if (AdjustCopiesBackFrom(CP, CopyMI) ||
920 RemoveCopyByCommutingDef(CP, CopyMI)) {
921 markAsJoined(CopyMI);
922 DEBUG(dbgs() << "\tTrivial!\n");
927 // Otherwise, we are unable to join the intervals.
928 DEBUG(dbgs() << "\tInterference!\n");
929 Again = true; // May be possible to coalesce later.
933 // Coalescing to a virtual register that is of a sub-register class of the
934 // other. Make sure the resulting register is set to the right register class.
935 if (CP.isCrossClass()) {
937 mri_->setRegClass(CP.getDstReg(), CP.getNewRC());
940 // Remember to delete the copy instruction.
941 markAsJoined(CopyMI);
943 UpdateRegDefsUses(CP);
945 // If we have extended the live range of a physical register, make sure we
946 // update live-in lists as well.
948 SmallVector<MachineBasicBlock*, 16> BlockSeq;
949 // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
950 // ranges for this, and they are preserved.
951 LiveInterval &SrcInt = li_->getInterval(CP.getSrcReg());
952 for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
954 li_->findLiveInMBBs(I->start, I->end, BlockSeq);
955 for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
956 MachineBasicBlock &block = *BlockSeq[idx];
957 if (!block.isLiveIn(CP.getDstReg()))
958 block.addLiveIn(CP.getDstReg());
964 // SrcReg is guarateed to be the register whose live interval that is
966 li_->removeInterval(CP.getSrcReg());
968 // Update regalloc hint.
969 tri_->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *mf_);
972 LiveInterval &DstInt = li_->getInterval(CP.getDstReg());
973 dbgs() << "\tJoined. Result = ";
974 DstInt.print(dbgs(), tri_);
982 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
983 /// compute what the resultant value numbers for each value in the input two
984 /// ranges will be. This is complicated by copies between the two which can
985 /// and will commonly cause multiple value numbers to be merged into one.
987 /// VN is the value number that we're trying to resolve. InstDefiningValue
988 /// keeps track of the new InstDefiningValue assignment for the result
989 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
990 /// whether a value in this or other is a copy from the opposite set.
991 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
992 /// already been assigned.
994 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
995 /// contains the value number the copy is from.
997 static unsigned ComputeUltimateVN(VNInfo *VNI,
998 SmallVector<VNInfo*, 16> &NewVNInfo,
999 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1000 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1001 SmallVector<int, 16> &ThisValNoAssignments,
1002 SmallVector<int, 16> &OtherValNoAssignments) {
1003 unsigned VN = VNI->id;
1005 // If the VN has already been computed, just return it.
1006 if (ThisValNoAssignments[VN] >= 0)
1007 return ThisValNoAssignments[VN];
1008 assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1010 // If this val is not a copy from the other val, then it must be a new value
1011 // number in the destination.
1012 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1013 if (I == ThisFromOther.end()) {
1014 NewVNInfo.push_back(VNI);
1015 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1017 VNInfo *OtherValNo = I->second;
1019 // Otherwise, this *is* a copy from the RHS. If the other side has already
1020 // been computed, return it.
1021 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1022 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1024 // Mark this value number as currently being computed, then ask what the
1025 // ultimate value # of the other value is.
1026 ThisValNoAssignments[VN] = -2;
1027 unsigned UltimateVN =
1028 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1029 OtherValNoAssignments, ThisValNoAssignments);
1030 return ThisValNoAssignments[VN] = UltimateVN;
1033 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1035 bool SimpleRegisterCoalescing::JoinIntervals(CoalescerPair &CP) {
1036 LiveInterval &RHS = li_->getInterval(CP.getSrcReg());
1037 DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), tri_); dbgs() << "\n"; });
1039 // If a live interval is a physical register, check for interference with any
1040 // aliases. The interference check implemented here is a bit more conservative
1041 // than the full interfeence check below. We allow overlapping live ranges
1042 // only when one is a copy of the other.
1044 for (const unsigned *AS = tri_->getAliasSet(CP.getDstReg()); *AS; ++AS){
1045 if (!li_->hasInterval(*AS))
1047 const LiveInterval &LHS = li_->getInterval(*AS);
1048 LiveInterval::const_iterator LI = LHS.begin();
1049 for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1051 LI = std::lower_bound(LI, LHS.end(), RI->start);
1052 // Does LHS have an overlapping live range starting before RI?
1053 if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1054 (RI->start != RI->valno->def ||
1055 !CP.isCoalescable(li_->getInstructionFromIndex(RI->start)))) {
1057 dbgs() << "\t\tInterference from alias: ";
1058 LHS.print(dbgs(), tri_);
1059 dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1064 // Check that LHS ranges beginning in this range are copies.
1065 for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1066 if (LI->start != LI->valno->def ||
1067 !CP.isCoalescable(li_->getInstructionFromIndex(LI->start))) {
1069 dbgs() << "\t\tInterference from alias: ";
1070 LHS.print(dbgs(), tri_);
1071 dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1080 // Compute the final value assignment, assuming that the live ranges can be
1082 SmallVector<int, 16> LHSValNoAssignments;
1083 SmallVector<int, 16> RHSValNoAssignments;
1084 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1085 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1086 SmallVector<VNInfo*, 16> NewVNInfo;
1088 LiveInterval &LHS = li_->getOrCreateInterval(CP.getDstReg());
1089 DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), tri_); dbgs() << "\n"; });
1091 // Loop over the value numbers of the LHS, seeing if any are defined from
1093 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1096 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy?
1099 // Never join with a register that has EarlyClobber redefs.
1100 if (VNI->hasRedefByEC())
1103 // DstReg is known to be a register in the LHS interval. If the src is
1104 // from the RHS interval, we can use its value #.
1105 if (!CP.isCoalescable(VNI->getCopy()))
1108 // Figure out the value # from the RHS.
1109 LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1110 // The copy could be to an aliased physreg.
1112 LHSValsDefinedFromRHS[VNI] = lr->valno;
1115 // Loop over the value numbers of the RHS, seeing if any are defined from
1117 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1120 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy?
1123 // Never join with a register that has EarlyClobber redefs.
1124 if (VNI->hasRedefByEC())
1127 // DstReg is known to be a register in the RHS interval. If the src is
1128 // from the LHS interval, we can use its value #.
1129 if (!CP.isCoalescable(VNI->getCopy()))
1132 // Figure out the value # from the LHS.
1133 LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1134 // The copy could be to an aliased physreg.
1136 RHSValsDefinedFromLHS[VNI] = lr->valno;
1139 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1140 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1141 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1143 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1146 unsigned VN = VNI->id;
1147 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1149 ComputeUltimateVN(VNI, NewVNInfo,
1150 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1151 LHSValNoAssignments, RHSValNoAssignments);
1153 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1156 unsigned VN = VNI->id;
1157 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1159 // If this value number isn't a copy from the LHS, it's a new number.
1160 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1161 NewVNInfo.push_back(VNI);
1162 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1166 ComputeUltimateVN(VNI, NewVNInfo,
1167 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1168 RHSValNoAssignments, LHSValNoAssignments);
1171 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1172 // interval lists to see if these intervals are coalescable.
1173 LiveInterval::const_iterator I = LHS.begin();
1174 LiveInterval::const_iterator IE = LHS.end();
1175 LiveInterval::const_iterator J = RHS.begin();
1176 LiveInterval::const_iterator JE = RHS.end();
1178 // Skip ahead until the first place of potential sharing.
1179 if (I != IE && J != JE) {
1180 if (I->start < J->start) {
1181 I = std::upper_bound(I, IE, J->start);
1182 if (I != LHS.begin()) --I;
1183 } else if (J->start < I->start) {
1184 J = std::upper_bound(J, JE, I->start);
1185 if (J != RHS.begin()) --J;
1189 while (I != IE && J != JE) {
1190 // Determine if these two live ranges overlap.
1192 if (I->start < J->start) {
1193 Overlaps = I->end > J->start;
1195 Overlaps = J->end > I->start;
1198 // If so, check value # info to determine if they are really different.
1200 // If the live range overlap will map to the same value number in the
1201 // result liverange, we can still coalesce them. If not, we can't.
1202 if (LHSValNoAssignments[I->valno->id] !=
1203 RHSValNoAssignments[J->valno->id])
1205 // If it's re-defined by an early clobber somewhere in the live range,
1206 // then conservatively abort coalescing.
1207 if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
1211 if (I->end < J->end)
1217 // Update kill info. Some live ranges are extended due to copy coalescing.
1218 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1219 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1220 VNInfo *VNI = I->first;
1221 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1222 if (VNI->hasPHIKill())
1223 NewVNInfo[LHSValID]->setHasPHIKill(true);
1226 // Update kill info. Some live ranges are extended due to copy coalescing.
1227 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1228 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1229 VNInfo *VNI = I->first;
1230 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1231 if (VNI->hasPHIKill())
1232 NewVNInfo[RHSValID]->setHasPHIKill(true);
1235 if (LHSValNoAssignments.empty())
1236 LHSValNoAssignments.push_back(-1);
1237 if (RHSValNoAssignments.empty())
1238 RHSValNoAssignments.push_back(-1);
1240 // If we get here, we know that we can coalesce the live ranges. Ask the
1241 // intervals to coalesce themselves now.
1242 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1248 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1249 // depth of the basic block (the unsigned), and then on the MBB number.
1250 struct DepthMBBCompare {
1251 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1252 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1253 // Deeper loops first
1254 if (LHS.first != RHS.first)
1255 return LHS.first > RHS.first;
1257 // Prefer blocks that are more connected in the CFG. This takes care of
1258 // the most difficult copies first while intervals are short.
1259 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1260 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1264 // As a last resort, sort by block number.
1265 return LHS.second->getNumber() < RHS.second->getNumber();
1270 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1271 std::vector<CopyRec> &TryAgain) {
1272 DEBUG(dbgs() << MBB->getName() << ":\n");
1274 SmallVector<CopyRec, 8> VirtCopies;
1275 SmallVector<CopyRec, 8> PhysCopies;
1276 SmallVector<CopyRec, 8> ImpDefCopies;
1277 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1279 MachineInstr *Inst = MII++;
1281 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1282 unsigned SrcReg, DstReg;
1283 if (Inst->isCopy()) {
1284 DstReg = Inst->getOperand(0).getReg();
1285 SrcReg = Inst->getOperand(1).getReg();
1286 } else if (Inst->isSubregToReg()) {
1287 DstReg = Inst->getOperand(0).getReg();
1288 SrcReg = Inst->getOperand(2).getReg();
1292 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1293 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1294 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1295 ImpDefCopies.push_back(CopyRec(Inst, 0));
1296 else if (SrcIsPhys || DstIsPhys)
1297 PhysCopies.push_back(CopyRec(Inst, 0));
1299 VirtCopies.push_back(CopyRec(Inst, 0));
1302 // Try coalescing implicit copies and insert_subreg <undef> first,
1303 // followed by copies to / from physical registers, then finally copies
1304 // from virtual registers to virtual registers.
1305 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1306 CopyRec &TheCopy = ImpDefCopies[i];
1308 if (!JoinCopy(TheCopy, Again))
1310 TryAgain.push_back(TheCopy);
1312 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1313 CopyRec &TheCopy = PhysCopies[i];
1315 if (!JoinCopy(TheCopy, Again))
1317 TryAgain.push_back(TheCopy);
1319 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1320 CopyRec &TheCopy = VirtCopies[i];
1322 if (!JoinCopy(TheCopy, Again))
1324 TryAgain.push_back(TheCopy);
1328 void SimpleRegisterCoalescing::joinIntervals() {
1329 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1331 std::vector<CopyRec> TryAgainList;
1332 if (loopInfo->empty()) {
1333 // If there are no loops in the function, join intervals in function order.
1334 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1336 CopyCoalesceInMBB(I, TryAgainList);
1338 // Otherwise, join intervals in inner loops before other intervals.
1339 // Unfortunately we can't just iterate over loop hierarchy here because
1340 // there may be more MBB's than BB's. Collect MBB's for sorting.
1342 // Join intervals in the function prolog first. We want to join physical
1343 // registers with virtual registers before the intervals got too long.
1344 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1345 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1346 MachineBasicBlock *MBB = I;
1347 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1350 // Sort by loop depth.
1351 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1353 // Finally, join intervals in loop nest order.
1354 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1355 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1358 // Joining intervals can allow other intervals to be joined. Iteratively join
1359 // until we make no progress.
1360 bool ProgressMade = true;
1361 while (ProgressMade) {
1362 ProgressMade = false;
1364 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1365 CopyRec &TheCopy = TryAgainList[i];
1370 bool Success = JoinCopy(TheCopy, Again);
1371 if (Success || !Again) {
1372 TheCopy.MI = 0; // Mark this one as done.
1373 ProgressMade = true;
1379 void SimpleRegisterCoalescing::releaseMemory() {
1380 JoinedCopies.clear();
1381 ReMatCopies.clear();
1385 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1387 mri_ = &fn.getRegInfo();
1388 tm_ = &fn.getTarget();
1389 tri_ = tm_->getRegisterInfo();
1390 tii_ = tm_->getInstrInfo();
1391 li_ = &getAnalysis<LiveIntervals>();
1392 ldv_ = &getAnalysis<LiveDebugVariables>();
1393 AA = &getAnalysis<AliasAnalysis>();
1394 loopInfo = &getAnalysis<MachineLoopInfo>();
1396 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1397 << "********** Function: "
1398 << ((Value*)mf_->getFunction())->getName() << '\n');
1400 if (VerifyCoalescing)
1401 mf_->verify(this, "Before register coalescing");
1403 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1404 E = tri_->regclass_end(); I != E; ++I)
1405 allocatableRCRegs_.insert(std::make_pair(*I,
1406 tri_->getAllocatableSet(fn, *I)));
1408 // Join (coalesce) intervals if requested.
1409 if (EnableJoining) {
1412 dbgs() << "********** INTERVALS POST JOINING **********\n";
1413 for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
1415 I->second->print(dbgs(), tri_);
1421 // Perform a final pass over the instructions and compute spill weights
1422 // and remove identity moves.
1423 SmallVector<unsigned, 4> DeadDefs;
1424 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1425 mbbi != mbbe; ++mbbi) {
1426 MachineBasicBlock* mbb = mbbi;
1427 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1429 MachineInstr *MI = mii;
1430 if (JoinedCopies.count(MI)) {
1431 // Delete all coalesced copies.
1432 bool DoDelete = true;
1433 assert(MI->isCopyLike() && "Unrecognized copy instruction");
1434 unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1435 if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1436 MI->getNumOperands() > 2)
1437 // Do not delete extract_subreg, insert_subreg of physical
1438 // registers unless the definition is dead. e.g.
1439 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1440 // or else the scavenger may complain. LowerSubregs will
1441 // delete them later.
1444 if (MI->allDefsAreDead()) {
1445 if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1446 li_->hasInterval(SrcReg))
1447 li_->shrinkToUses(&li_->getInterval(SrcReg));
1451 // We need the instruction to adjust liveness, so make it a KILL.
1452 if (MI->isSubregToReg()) {
1453 MI->RemoveOperand(3);
1454 MI->RemoveOperand(1);
1456 MI->setDesc(tii_->get(TargetOpcode::KILL));
1457 mii = llvm::next(mii);
1459 li_->RemoveMachineInstrFromMaps(MI);
1460 mii = mbbi->erase(mii);
1466 // Now check if this is a remat'ed def instruction which is now dead.
1467 if (ReMatDefs.count(MI)) {
1469 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1470 const MachineOperand &MO = MI->getOperand(i);
1473 unsigned Reg = MO.getReg();
1476 if (TargetRegisterInfo::isVirtualRegister(Reg))
1477 DeadDefs.push_back(Reg);
1480 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1481 !mri_->use_nodbg_empty(Reg)) {
1487 while (!DeadDefs.empty()) {
1488 unsigned DeadDef = DeadDefs.back();
1489 DeadDefs.pop_back();
1490 RemoveDeadDef(li_->getInterval(DeadDef), MI);
1492 li_->RemoveMachineInstrFromMaps(mii);
1493 mii = mbbi->erase(mii);
1501 // Check for now unnecessary kill flags.
1502 if (li_->isNotInMIMap(MI)) continue;
1503 SlotIndex DefIdx = li_->getInstructionIndex(MI).getDefIndex();
1504 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1505 MachineOperand &MO = MI->getOperand(i);
1506 if (!MO.isReg() || !MO.isKill()) continue;
1507 unsigned reg = MO.getReg();
1508 if (!reg || !li_->hasInterval(reg)) continue;
1509 if (!li_->getInterval(reg).killedAt(DefIdx)) {
1510 MO.setIsKill(false);
1513 // When leaving a kill flag on a physreg, check if any subregs should
1515 if (!TargetRegisterInfo::isPhysicalRegister(reg))
1517 for (const unsigned *SR = tri_->getSubRegisters(reg);
1518 unsigned S = *SR; ++SR)
1519 if (li_->hasInterval(S) && li_->getInterval(S).liveAt(DefIdx))
1520 MI->addRegisterDefined(S, tri_);
1526 DEBUG(ldv_->dump());
1527 if (VerifyCoalescing)
1528 mf_->verify(this, "After register coalescing");
1532 /// print - Implement the dump method.
1533 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
1537 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1538 return new SimpleRegisterCoalescing();
1541 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1542 DEFINING_FILE_FOR(SimpleRegisterCoalescing)