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 "RegisterCoalescer.h"
17 #include "VirtRegMap.h"
18 #include "LiveDebugVariables.h"
19 #include "RegisterCoalescer.h"
20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
21 #include "llvm/Value.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/CodeGen/MachineLoopInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/Passes.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 = RegClassInfo.getNumAllocatableRegs(RC) * 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 = RegClassInfo.getNumAllocatableRegs(NewRC);
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 = RegClassInfo.getNumAllocatableRegs(SrcRC);
825 if (NewUses*SrcSize*SrcRCCount > 2*SrcUses*NewSize*NewRCCount)
828 if (DstRC != NewRC && DstSize > ThresSize) {
829 unsigned DstRCCount = RegClassInfo.getNumAllocatableRegs(DstRC);
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(MachineInstr *CopyMI, bool &Again) {
845 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
846 return false; // Already done.
848 DEBUG(dbgs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
850 CoalescerPair CP(*tii_, *tri_);
851 if (!CP.setRegisters(CopyMI)) {
852 DEBUG(dbgs() << "\tNot coalescable.\n");
856 // If they are already joined we continue.
857 if (CP.getSrcReg() == CP.getDstReg()) {
858 markAsJoined(CopyMI);
859 DEBUG(dbgs() << "\tCopy already coalesced.\n");
860 return false; // Not coalescable.
863 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), tri_)
864 << " with " << PrintReg(CP.getDstReg(), tri_, CP.getSubIdx())
869 if (!shouldJoinPhys(CP)) {
870 // Before giving up coalescing, if definition of source is defined by
871 // trivial computation, try rematerializing it.
872 if (!CP.isFlipped() &&
873 ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()), true,
874 CP.getDstReg(), 0, CopyMI))
879 // Avoid constraining virtual register regclass too much.
880 if (CP.isCrossClass()) {
881 DEBUG(dbgs() << "\tCross-class to " << CP.getNewRC()->getName() << ".\n");
882 if (DisableCrossClassJoin) {
883 DEBUG(dbgs() << "\tCross-class joins disabled.\n");
886 if (!isWinToJoinCrossClass(CP.getSrcReg(), CP.getDstReg(),
887 mri_->getRegClass(CP.getSrcReg()),
888 mri_->getRegClass(CP.getDstReg()),
890 DEBUG(dbgs() << "\tAvoid coalescing to constrained register class.\n");
891 Again = true; // May be possible to coalesce later.
896 // When possible, let DstReg be the larger interval.
897 if (!CP.getSubIdx() && li_->getInterval(CP.getSrcReg()).ranges.size() >
898 li_->getInterval(CP.getDstReg()).ranges.size())
902 // Okay, attempt to join these two intervals. On failure, this returns false.
903 // Otherwise, if one of the intervals being joined is a physreg, this method
904 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
905 // been modified, so we can use this information below to update aliases.
906 if (!JoinIntervals(CP)) {
907 // Coalescing failed.
909 // If definition of source is defined by trivial computation, try
910 // rematerializing it.
911 if (!CP.isFlipped() &&
912 ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()), true,
913 CP.getDstReg(), 0, CopyMI))
916 // If we can eliminate the copy without merging the live ranges, do so now.
917 if (!CP.isPartial()) {
918 if (AdjustCopiesBackFrom(CP, CopyMI) ||
919 RemoveCopyByCommutingDef(CP, CopyMI)) {
920 markAsJoined(CopyMI);
921 DEBUG(dbgs() << "\tTrivial!\n");
926 // Otherwise, we are unable to join the intervals.
927 DEBUG(dbgs() << "\tInterference!\n");
928 Again = true; // May be possible to coalesce later.
932 // Coalescing to a virtual register that is of a sub-register class of the
933 // other. Make sure the resulting register is set to the right register class.
934 if (CP.isCrossClass()) {
936 mri_->setRegClass(CP.getDstReg(), CP.getNewRC());
939 // Remember to delete the copy instruction.
940 markAsJoined(CopyMI);
942 UpdateRegDefsUses(CP);
944 // If we have extended the live range of a physical register, make sure we
945 // update live-in lists as well.
947 SmallVector<MachineBasicBlock*, 16> BlockSeq;
948 // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
949 // ranges for this, and they are preserved.
950 LiveInterval &SrcInt = li_->getInterval(CP.getSrcReg());
951 for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
953 li_->findLiveInMBBs(I->start, I->end, BlockSeq);
954 for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
955 MachineBasicBlock &block = *BlockSeq[idx];
956 if (!block.isLiveIn(CP.getDstReg()))
957 block.addLiveIn(CP.getDstReg());
963 // SrcReg is guarateed to be the register whose live interval that is
965 li_->removeInterval(CP.getSrcReg());
967 // Update regalloc hint.
968 tri_->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *mf_);
971 LiveInterval &DstInt = li_->getInterval(CP.getDstReg());
972 dbgs() << "\tJoined. Result = ";
973 DstInt.print(dbgs(), tri_);
981 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
982 /// compute what the resultant value numbers for each value in the input two
983 /// ranges will be. This is complicated by copies between the two which can
984 /// and will commonly cause multiple value numbers to be merged into one.
986 /// VN is the value number that we're trying to resolve. InstDefiningValue
987 /// keeps track of the new InstDefiningValue assignment for the result
988 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
989 /// whether a value in this or other is a copy from the opposite set.
990 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
991 /// already been assigned.
993 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
994 /// contains the value number the copy is from.
996 static unsigned ComputeUltimateVN(VNInfo *VNI,
997 SmallVector<VNInfo*, 16> &NewVNInfo,
998 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
999 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1000 SmallVector<int, 16> &ThisValNoAssignments,
1001 SmallVector<int, 16> &OtherValNoAssignments) {
1002 unsigned VN = VNI->id;
1004 // If the VN has already been computed, just return it.
1005 if (ThisValNoAssignments[VN] >= 0)
1006 return ThisValNoAssignments[VN];
1007 assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1009 // If this val is not a copy from the other val, then it must be a new value
1010 // number in the destination.
1011 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1012 if (I == ThisFromOther.end()) {
1013 NewVNInfo.push_back(VNI);
1014 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1016 VNInfo *OtherValNo = I->second;
1018 // Otherwise, this *is* a copy from the RHS. If the other side has already
1019 // been computed, return it.
1020 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1021 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1023 // Mark this value number as currently being computed, then ask what the
1024 // ultimate value # of the other value is.
1025 ThisValNoAssignments[VN] = -2;
1026 unsigned UltimateVN =
1027 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1028 OtherValNoAssignments, ThisValNoAssignments);
1029 return ThisValNoAssignments[VN] = UltimateVN;
1032 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1034 bool SimpleRegisterCoalescing::JoinIntervals(CoalescerPair &CP) {
1035 LiveInterval &RHS = li_->getInterval(CP.getSrcReg());
1036 DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), tri_); dbgs() << "\n"; });
1038 // If a live interval is a physical register, check for interference with any
1039 // aliases. The interference check implemented here is a bit more conservative
1040 // than the full interfeence check below. We allow overlapping live ranges
1041 // only when one is a copy of the other.
1043 for (const unsigned *AS = tri_->getAliasSet(CP.getDstReg()); *AS; ++AS){
1044 if (!li_->hasInterval(*AS))
1046 const LiveInterval &LHS = li_->getInterval(*AS);
1047 LiveInterval::const_iterator LI = LHS.begin();
1048 for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1050 LI = std::lower_bound(LI, LHS.end(), RI->start);
1051 // Does LHS have an overlapping live range starting before RI?
1052 if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1053 (RI->start != RI->valno->def ||
1054 !CP.isCoalescable(li_->getInstructionFromIndex(RI->start)))) {
1056 dbgs() << "\t\tInterference from alias: ";
1057 LHS.print(dbgs(), tri_);
1058 dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1063 // Check that LHS ranges beginning in this range are copies.
1064 for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1065 if (LI->start != LI->valno->def ||
1066 !CP.isCoalescable(li_->getInstructionFromIndex(LI->start))) {
1068 dbgs() << "\t\tInterference from alias: ";
1069 LHS.print(dbgs(), tri_);
1070 dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1079 // Compute the final value assignment, assuming that the live ranges can be
1081 SmallVector<int, 16> LHSValNoAssignments;
1082 SmallVector<int, 16> RHSValNoAssignments;
1083 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1084 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1085 SmallVector<VNInfo*, 16> NewVNInfo;
1087 LiveInterval &LHS = li_->getOrCreateInterval(CP.getDstReg());
1088 DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), tri_); dbgs() << "\n"; });
1090 // Loop over the value numbers of the LHS, seeing if any are defined from
1092 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1095 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy?
1098 // Never join with a register that has EarlyClobber redefs.
1099 if (VNI->hasRedefByEC())
1102 // DstReg is known to be a register in the LHS interval. If the src is
1103 // from the RHS interval, we can use its value #.
1104 if (!CP.isCoalescable(VNI->getCopy()))
1107 // Figure out the value # from the RHS.
1108 LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1109 // The copy could be to an aliased physreg.
1111 LHSValsDefinedFromRHS[VNI] = lr->valno;
1114 // Loop over the value numbers of the RHS, seeing if any are defined from
1116 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1119 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy?
1122 // Never join with a register that has EarlyClobber redefs.
1123 if (VNI->hasRedefByEC())
1126 // DstReg is known to be a register in the RHS interval. If the src is
1127 // from the LHS interval, we can use its value #.
1128 if (!CP.isCoalescable(VNI->getCopy()))
1131 // Figure out the value # from the LHS.
1132 LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1133 // The copy could be to an aliased physreg.
1135 RHSValsDefinedFromLHS[VNI] = lr->valno;
1138 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1139 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1140 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1142 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1145 unsigned VN = VNI->id;
1146 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1148 ComputeUltimateVN(VNI, NewVNInfo,
1149 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1150 LHSValNoAssignments, RHSValNoAssignments);
1152 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1155 unsigned VN = VNI->id;
1156 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1158 // If this value number isn't a copy from the LHS, it's a new number.
1159 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1160 NewVNInfo.push_back(VNI);
1161 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1165 ComputeUltimateVN(VNI, NewVNInfo,
1166 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1167 RHSValNoAssignments, LHSValNoAssignments);
1170 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1171 // interval lists to see if these intervals are coalescable.
1172 LiveInterval::const_iterator I = LHS.begin();
1173 LiveInterval::const_iterator IE = LHS.end();
1174 LiveInterval::const_iterator J = RHS.begin();
1175 LiveInterval::const_iterator JE = RHS.end();
1177 // Skip ahead until the first place of potential sharing.
1178 if (I != IE && J != JE) {
1179 if (I->start < J->start) {
1180 I = std::upper_bound(I, IE, J->start);
1181 if (I != LHS.begin()) --I;
1182 } else if (J->start < I->start) {
1183 J = std::upper_bound(J, JE, I->start);
1184 if (J != RHS.begin()) --J;
1188 while (I != IE && J != JE) {
1189 // Determine if these two live ranges overlap.
1191 if (I->start < J->start) {
1192 Overlaps = I->end > J->start;
1194 Overlaps = J->end > I->start;
1197 // If so, check value # info to determine if they are really different.
1199 // If the live range overlap will map to the same value number in the
1200 // result liverange, we can still coalesce them. If not, we can't.
1201 if (LHSValNoAssignments[I->valno->id] !=
1202 RHSValNoAssignments[J->valno->id])
1204 // If it's re-defined by an early clobber somewhere in the live range,
1205 // then conservatively abort coalescing.
1206 if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
1210 if (I->end < J->end)
1216 // Update kill info. Some live ranges are extended due to copy coalescing.
1217 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1218 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1219 VNInfo *VNI = I->first;
1220 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1221 if (VNI->hasPHIKill())
1222 NewVNInfo[LHSValID]->setHasPHIKill(true);
1225 // Update kill info. Some live ranges are extended due to copy coalescing.
1226 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1227 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1228 VNInfo *VNI = I->first;
1229 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1230 if (VNI->hasPHIKill())
1231 NewVNInfo[RHSValID]->setHasPHIKill(true);
1234 if (LHSValNoAssignments.empty())
1235 LHSValNoAssignments.push_back(-1);
1236 if (RHSValNoAssignments.empty())
1237 RHSValNoAssignments.push_back(-1);
1239 // If we get here, we know that we can coalesce the live ranges. Ask the
1240 // intervals to coalesce themselves now.
1241 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1247 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1248 // depth of the basic block (the unsigned), and then on the MBB number.
1249 struct DepthMBBCompare {
1250 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1251 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1252 // Deeper loops first
1253 if (LHS.first != RHS.first)
1254 return LHS.first > RHS.first;
1256 // Prefer blocks that are more connected in the CFG. This takes care of
1257 // the most difficult copies first while intervals are short.
1258 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1259 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1263 // As a last resort, sort by block number.
1264 return LHS.second->getNumber() < RHS.second->getNumber();
1269 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1270 std::vector<MachineInstr*> &TryAgain) {
1271 DEBUG(dbgs() << MBB->getName() << ":\n");
1273 SmallVector<MachineInstr*, 8> VirtCopies;
1274 SmallVector<MachineInstr*, 8> PhysCopies;
1275 SmallVector<MachineInstr*, 8> ImpDefCopies;
1276 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1278 MachineInstr *Inst = MII++;
1280 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1281 unsigned SrcReg, DstReg;
1282 if (Inst->isCopy()) {
1283 DstReg = Inst->getOperand(0).getReg();
1284 SrcReg = Inst->getOperand(1).getReg();
1285 } else if (Inst->isSubregToReg()) {
1286 DstReg = Inst->getOperand(0).getReg();
1287 SrcReg = Inst->getOperand(2).getReg();
1291 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1292 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1293 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1294 ImpDefCopies.push_back(Inst);
1295 else if (SrcIsPhys || DstIsPhys)
1296 PhysCopies.push_back(Inst);
1298 VirtCopies.push_back(Inst);
1301 // Try coalescing implicit copies and insert_subreg <undef> first,
1302 // followed by copies to / from physical registers, then finally copies
1303 // from virtual registers to virtual registers.
1304 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1305 MachineInstr *TheCopy = ImpDefCopies[i];
1307 if (!JoinCopy(TheCopy, Again))
1309 TryAgain.push_back(TheCopy);
1311 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1312 MachineInstr *TheCopy = PhysCopies[i];
1314 if (!JoinCopy(TheCopy, Again))
1316 TryAgain.push_back(TheCopy);
1318 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1319 MachineInstr *TheCopy = VirtCopies[i];
1321 if (!JoinCopy(TheCopy, Again))
1323 TryAgain.push_back(TheCopy);
1327 void SimpleRegisterCoalescing::joinIntervals() {
1328 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1330 std::vector<MachineInstr*> TryAgainList;
1331 if (loopInfo->empty()) {
1332 // If there are no loops in the function, join intervals in function order.
1333 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1335 CopyCoalesceInMBB(I, TryAgainList);
1337 // Otherwise, join intervals in inner loops before other intervals.
1338 // Unfortunately we can't just iterate over loop hierarchy here because
1339 // there may be more MBB's than BB's. Collect MBB's for sorting.
1341 // Join intervals in the function prolog first. We want to join physical
1342 // registers with virtual registers before the intervals got too long.
1343 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1344 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1345 MachineBasicBlock *MBB = I;
1346 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1349 // Sort by loop depth.
1350 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1352 // Finally, join intervals in loop nest order.
1353 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1354 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1357 // Joining intervals can allow other intervals to be joined. Iteratively join
1358 // until we make no progress.
1359 bool ProgressMade = true;
1360 while (ProgressMade) {
1361 ProgressMade = false;
1363 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1364 MachineInstr *&TheCopy = TryAgainList[i];
1369 bool Success = JoinCopy(TheCopy, Again);
1370 if (Success || !Again) {
1371 TheCopy= 0; // Mark this one as done.
1372 ProgressMade = true;
1378 void SimpleRegisterCoalescing::releaseMemory() {
1379 JoinedCopies.clear();
1380 ReMatCopies.clear();
1384 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1386 mri_ = &fn.getRegInfo();
1387 tm_ = &fn.getTarget();
1388 tri_ = tm_->getRegisterInfo();
1389 tii_ = tm_->getInstrInfo();
1390 li_ = &getAnalysis<LiveIntervals>();
1391 ldv_ = &getAnalysis<LiveDebugVariables>();
1392 AA = &getAnalysis<AliasAnalysis>();
1393 loopInfo = &getAnalysis<MachineLoopInfo>();
1395 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1396 << "********** Function: "
1397 << ((Value*)mf_->getFunction())->getName() << '\n');
1399 if (VerifyCoalescing)
1400 mf_->verify(this, "Before register coalescing");
1402 RegClassInfo.runOnMachineFunction(fn);
1404 // Join (coalesce) intervals if requested.
1405 if (EnableJoining) {
1408 dbgs() << "********** INTERVALS POST JOINING **********\n";
1409 for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
1411 I->second->print(dbgs(), tri_);
1417 // Perform a final pass over the instructions and compute spill weights
1418 // and remove identity moves.
1419 SmallVector<unsigned, 4> DeadDefs;
1420 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1421 mbbi != mbbe; ++mbbi) {
1422 MachineBasicBlock* mbb = mbbi;
1423 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1425 MachineInstr *MI = mii;
1426 if (JoinedCopies.count(MI)) {
1427 // Delete all coalesced copies.
1428 bool DoDelete = true;
1429 assert(MI->isCopyLike() && "Unrecognized copy instruction");
1430 unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1431 if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1432 MI->getNumOperands() > 2)
1433 // Do not delete extract_subreg, insert_subreg of physical
1434 // registers unless the definition is dead. e.g.
1435 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1436 // or else the scavenger may complain. LowerSubregs will
1437 // delete them later.
1440 if (MI->allDefsAreDead()) {
1441 if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1442 li_->hasInterval(SrcReg))
1443 li_->shrinkToUses(&li_->getInterval(SrcReg));
1447 // We need the instruction to adjust liveness, so make it a KILL.
1448 if (MI->isSubregToReg()) {
1449 MI->RemoveOperand(3);
1450 MI->RemoveOperand(1);
1452 MI->setDesc(tii_->get(TargetOpcode::KILL));
1453 mii = llvm::next(mii);
1455 li_->RemoveMachineInstrFromMaps(MI);
1456 mii = mbbi->erase(mii);
1462 // Now check if this is a remat'ed def instruction which is now dead.
1463 if (ReMatDefs.count(MI)) {
1465 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1466 const MachineOperand &MO = MI->getOperand(i);
1469 unsigned Reg = MO.getReg();
1472 if (TargetRegisterInfo::isVirtualRegister(Reg))
1473 DeadDefs.push_back(Reg);
1476 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1477 !mri_->use_nodbg_empty(Reg)) {
1483 while (!DeadDefs.empty()) {
1484 unsigned DeadDef = DeadDefs.back();
1485 DeadDefs.pop_back();
1486 RemoveDeadDef(li_->getInterval(DeadDef), MI);
1488 li_->RemoveMachineInstrFromMaps(mii);
1489 mii = mbbi->erase(mii);
1497 // Check for now unnecessary kill flags.
1498 if (li_->isNotInMIMap(MI)) continue;
1499 SlotIndex DefIdx = li_->getInstructionIndex(MI).getDefIndex();
1500 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1501 MachineOperand &MO = MI->getOperand(i);
1502 if (!MO.isReg() || !MO.isKill()) continue;
1503 unsigned reg = MO.getReg();
1504 if (!reg || !li_->hasInterval(reg)) continue;
1505 if (!li_->getInterval(reg).killedAt(DefIdx)) {
1506 MO.setIsKill(false);
1509 // When leaving a kill flag on a physreg, check if any subregs should
1511 if (!TargetRegisterInfo::isPhysicalRegister(reg))
1513 for (const unsigned *SR = tri_->getSubRegisters(reg);
1514 unsigned S = *SR; ++SR)
1515 if (li_->hasInterval(S) && li_->getInterval(S).liveAt(DefIdx))
1516 MI->addRegisterDefined(S, tri_);
1522 DEBUG(ldv_->dump());
1523 if (VerifyCoalescing)
1524 mf_->verify(this, "After register coalescing");
1528 /// print - Implement the dump method.
1529 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
1533 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1534 return new SimpleRegisterCoalescing();
1537 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1538 DEFINING_FILE_FOR(SimpleRegisterCoalescing)