1 //===- RegisterCoalescer.cpp - Generic Register Coalescing Interface -------==//
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 the generic RegisterCoalescer interface which
11 // is used as the common interface used by all clients and
12 // implementations of register coalescing.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "regcoalescing"
17 #include "RegisterCoalescer.h"
18 #include "VirtRegMap.h"
19 #include "LiveDebugVariables.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Value.h"
23 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
29 #include "llvm/Analysis/AliasAnalysis.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/CodeGen/MachineLoopInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/Passes.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/ADT/OwningPtr.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/STLExtras.h"
50 STATISTIC(numJoins , "Number of interval joins performed");
51 STATISTIC(numCrossRCs , "Number of cross class joins performed");
52 STATISTIC(numCommutes , "Number of instruction commuting performed");
53 STATISTIC(numExtends , "Number of copies extended");
54 STATISTIC(NumReMats , "Number of instructions re-materialized");
55 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
56 STATISTIC(numAborts , "Number of times interval joining aborted");
58 char SimpleRegisterCoalescing::ID = 0;
60 EnableJoining("join-liveintervals",
61 cl::desc("Coalesce copies (default=true)"),
65 DisableCrossClassJoin("disable-cross-class-join",
66 cl::desc("Avoid coalescing cross register class copies"),
67 cl::init(false), cl::Hidden);
70 EnablePhysicalJoin("join-physregs",
71 cl::desc("Join physical register copies"),
72 cl::init(false), cl::Hidden);
75 VerifyCoalescing("verify-coalescing",
76 cl::desc("Verify machine instrs before and after register coalescing"),
79 INITIALIZE_AG_PASS_BEGIN(SimpleRegisterCoalescing, RegisterCoalescer,
80 "simple-register-coalescing", "Simple Register Coalescing",
82 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
83 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
84 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
85 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
86 INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination)
87 INITIALIZE_PASS_DEPENDENCY(PHIElimination)
88 INITIALIZE_PASS_DEPENDENCY(TwoAddressInstructionPass)
89 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
90 INITIALIZE_AG_PASS_END(SimpleRegisterCoalescing, RegisterCoalescer,
91 "simple-register-coalescing", "Simple Register Coalescing",
94 char &llvm::SimpleRegisterCoalescingID = SimpleRegisterCoalescing::ID;
96 // Register the RegisterCoalescer interface, providing a nice name to refer to.
97 INITIALIZE_ANALYSIS_GROUP(RegisterCoalescer, "Register Coalescer",
98 SimpleRegisterCoalescing)
99 char RegisterCoalescer::ID = 0;
101 // RegisterCoalescer destructor: DO NOT move this to the header file
102 // for RegisterCoalescer or else clients of the RegisterCoalescer
103 // class may not depend on the RegisterCoalescer.o file in the current
104 // .a file, causing alias analysis support to not be included in the
107 RegisterCoalescer::~RegisterCoalescer() {}
109 unsigned CoalescerPair::compose(unsigned a, unsigned b) const {
112 return tri_.composeSubRegIndices(a, b);
115 bool CoalescerPair::isMoveInstr(const MachineInstr *MI,
116 unsigned &Src, unsigned &Dst,
117 unsigned &SrcSub, unsigned &DstSub) const {
119 Dst = MI->getOperand(0).getReg();
120 DstSub = MI->getOperand(0).getSubReg();
121 Src = MI->getOperand(1).getReg();
122 SrcSub = MI->getOperand(1).getSubReg();
123 } else if (MI->isSubregToReg()) {
124 Dst = MI->getOperand(0).getReg();
125 DstSub = compose(MI->getOperand(0).getSubReg(), MI->getOperand(3).getImm());
126 Src = MI->getOperand(2).getReg();
127 SrcSub = MI->getOperand(2).getSubReg();
133 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
134 srcReg_ = dstReg_ = subIdx_ = 0;
136 flipped_ = crossClass_ = false;
138 unsigned Src, Dst, SrcSub, DstSub;
139 if (!isMoveInstr(MI, Src, Dst, SrcSub, DstSub))
141 partial_ = SrcSub || DstSub;
143 // If one register is a physreg, it must be Dst.
144 if (TargetRegisterInfo::isPhysicalRegister(Src)) {
145 if (TargetRegisterInfo::isPhysicalRegister(Dst))
148 std::swap(SrcSub, DstSub);
152 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
154 if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
155 // Eliminate DstSub on a physreg.
157 Dst = tri_.getSubReg(Dst, DstSub);
158 if (!Dst) return false;
162 // Eliminate SrcSub by picking a corresponding Dst superregister.
164 Dst = tri_.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
165 if (!Dst) return false;
167 } else if (!MRI.getRegClass(Src)->contains(Dst)) {
171 // Both registers are virtual.
173 // Both registers have subreg indices.
174 if (SrcSub && DstSub) {
175 // For now we only handle the case of identical indices in commensurate
176 // registers: Dreg:ssub_1 + Dreg:ssub_1 -> Dreg
177 // FIXME: Handle Qreg:ssub_3 + Dreg:ssub_1 as QReg:dsub_1 + Dreg.
178 if (SrcSub != DstSub)
180 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
181 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
182 if (!getCommonSubClass(DstRC, SrcRC))
187 // There can be no SrcSub.
192 assert(!flipped_ && "Unexpected flip");
196 // Find the new register class.
197 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
198 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
200 newRC_ = tri_.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
202 newRC_ = getCommonSubClass(DstRC, SrcRC);
205 crossClass_ = newRC_ != DstRC || newRC_ != SrcRC;
207 // Check our invariants
208 assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
209 assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
210 "Cannot have a physical SubIdx");
217 bool CoalescerPair::flip() {
218 if (subIdx_ || TargetRegisterInfo::isPhysicalRegister(dstReg_))
220 std::swap(srcReg_, dstReg_);
221 flipped_ = !flipped_;
225 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
228 unsigned Src, Dst, SrcSub, DstSub;
229 if (!isMoveInstr(MI, Src, Dst, SrcSub, DstSub))
232 // Find the virtual register that is srcReg_.
233 if (Dst == srcReg_) {
235 std::swap(SrcSub, DstSub);
236 } else if (Src != srcReg_) {
240 // Now check that Dst matches dstReg_.
241 if (TargetRegisterInfo::isPhysicalRegister(dstReg_)) {
242 if (!TargetRegisterInfo::isPhysicalRegister(Dst))
244 assert(!subIdx_ && "Inconsistent CoalescerPair state.");
245 // DstSub could be set for a physreg from INSERT_SUBREG.
247 Dst = tri_.getSubReg(Dst, DstSub);
250 return dstReg_ == Dst;
251 // This is a partial register copy. Check that the parts match.
252 return tri_.getSubReg(dstReg_, SrcSub) == Dst;
254 // dstReg_ is virtual.
257 // Registers match, do the subregisters line up?
258 return compose(subIdx_, SrcSub) == DstSub;
262 // Because of the way .a files work, we must force the SimpleRC
263 // implementation to be pulled in if the RegisterCoalescer classes are
264 // pulled in. Otherwise we run the risk of RegisterCoalescer being
265 // used, but the default implementation not being linked into the tool
267 DEFINING_FILE_FOR(RegisterCoalescer)
269 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
270 AU.setPreservesCFG();
271 AU.addRequired<AliasAnalysis>();
272 AU.addRequired<LiveIntervals>();
273 AU.addPreserved<LiveIntervals>();
274 AU.addRequired<LiveDebugVariables>();
275 AU.addPreserved<LiveDebugVariables>();
276 AU.addPreserved<SlotIndexes>();
277 AU.addRequired<MachineLoopInfo>();
278 AU.addPreserved<MachineLoopInfo>();
279 AU.addPreservedID(MachineDominatorsID);
280 AU.addPreservedID(StrongPHIEliminationID);
281 AU.addPreservedID(PHIEliminationID);
282 AU.addPreservedID(TwoAddressInstructionPassID);
283 MachineFunctionPass::getAnalysisUsage(AU);
286 void SimpleRegisterCoalescing::markAsJoined(MachineInstr *CopyMI) {
287 /// Joined copies are not deleted immediately, but kept in JoinedCopies.
288 JoinedCopies.insert(CopyMI);
290 /// Mark all register operands of CopyMI as <undef> so they won't affect dead
291 /// code elimination.
292 for (MachineInstr::mop_iterator I = CopyMI->operands_begin(),
293 E = CopyMI->operands_end(); I != E; ++I)
298 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
299 /// being the source and IntB being the dest, thus this defines a value number
300 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
301 /// see if we can merge these two pieces of B into a single value number,
302 /// eliminating a copy. For example:
306 /// B1 = A3 <- this copy
308 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
309 /// value number to be replaced with B0 (which simplifies the B liveinterval).
311 /// This returns true if an interval was modified.
313 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(const CoalescerPair &CP,
314 MachineInstr *CopyMI) {
315 // Bail if there is no dst interval - can happen when merging physical subreg
317 if (!li_->hasInterval(CP.getDstReg()))
321 li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
323 li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
324 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
326 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
327 // the example above.
328 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
329 if (BLR == IntB.end()) return false;
330 VNInfo *BValNo = BLR->valno;
332 // Get the location that B is defined at. Two options: either this value has
333 // an unknown definition point or it is defined at CopyIdx. If unknown, we
335 if (!BValNo->isDefByCopy()) return false;
336 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
338 // AValNo is the value number in A that defines the copy, A3 in the example.
339 SlotIndex CopyUseIdx = CopyIdx.getUseIndex();
340 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
341 // The live range might not exist after fun with physreg coalescing.
342 if (ALR == IntA.end()) return false;
343 VNInfo *AValNo = ALR->valno;
344 // If it's re-defined by an early clobber somewhere in the live range, then
345 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
347 // 172 %ECX<def> = MOV32rr %reg1039<kill>
348 // 180 INLINEASM <es:subl $5,$1
349 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9,
351 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
352 // 188 %EAX<def> = MOV32rr %EAX<kill>
353 // 196 %ECX<def> = MOV32rr %ECX<kill>
354 // 204 %ECX<def> = MOV32rr %ECX<kill>
355 // 212 %EAX<def> = MOV32rr %EAX<kill>
356 // 220 %EAX<def> = MOV32rr %EAX
357 // 228 %reg1039<def> = MOV32rr %ECX<kill>
358 // The early clobber operand ties ECX input to the ECX def.
360 // The live interval of ECX is represented as this:
361 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
362 // The coalescer has no idea there was a def in the middle of [174,230].
363 if (AValNo->hasRedefByEC())
366 // If AValNo is defined as a copy from IntB, we can potentially process this.
367 // Get the instruction that defines this value number.
368 if (!CP.isCoalescable(AValNo->getCopy()))
371 // Get the LiveRange in IntB that this value number starts with.
372 LiveInterval::iterator ValLR =
373 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
374 if (ValLR == IntB.end())
377 // Make sure that the end of the live range is inside the same block as
379 MachineInstr *ValLREndInst =
380 li_->getInstructionFromIndex(ValLR->end.getPrevSlot());
381 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
384 // Okay, we now know that ValLR ends in the same block that the CopyMI
385 // live-range starts. If there are no intervening live ranges between them in
386 // IntB, we can merge them.
387 if (ValLR+1 != BLR) return false;
389 // If a live interval is a physical register, conservatively check if any
390 // of its aliases is overlapping the live interval of the virtual register.
391 // If so, do not coalesce.
392 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
393 for (const unsigned *AS = tri_->getAliasSet(IntB.reg); *AS; ++AS)
394 if (li_->hasInterval(*AS) && IntA.overlaps(li_->getInterval(*AS))) {
396 dbgs() << "\t\tInterfere with alias ";
397 li_->getInterval(*AS).print(dbgs(), tri_);
404 dbgs() << "Extending: ";
405 IntB.print(dbgs(), tri_);
408 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
409 // We are about to delete CopyMI, so need to remove it as the 'instruction
410 // that defines this value #'. Update the valnum with the new defining
412 BValNo->def = FillerStart;
415 // Okay, we can merge them. We need to insert a new liverange:
416 // [ValLR.end, BLR.begin) of either value number, then we merge the
417 // two value numbers.
418 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
420 // If the IntB live range is assigned to a physical register, and if that
421 // physreg has sub-registers, update their live intervals as well.
422 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
423 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
424 if (!li_->hasInterval(*SR))
426 LiveInterval &SRLI = li_->getInterval(*SR);
427 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
428 SRLI.getNextValue(FillerStart, 0,
429 li_->getVNInfoAllocator())));
433 // Okay, merge "B1" into the same value number as "B0".
434 if (BValNo != ValLR->valno) {
435 // If B1 is killed by a PHI, then the merged live range must also be killed
436 // by the same PHI, as B0 and B1 can not overlap.
437 bool HasPHIKill = BValNo->hasPHIKill();
438 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
440 ValLR->valno->setHasPHIKill(true);
443 dbgs() << " result = ";
444 IntB.print(dbgs(), tri_);
448 // If the source instruction was killing the source register before the
449 // merge, unset the isKill marker given the live range has been extended.
450 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
452 ValLREndInst->getOperand(UIdx).setIsKill(false);
455 // If the copy instruction was killing the destination register before the
456 // merge, find the last use and trim the live range. That will also add the
458 if (ALR->end == CopyIdx)
459 li_->shrinkToUses(&IntA);
465 /// HasOtherReachingDefs - Return true if there are definitions of IntB
466 /// other than BValNo val# that can reach uses of AValno val# of IntA.
467 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
471 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
473 if (AI->valno != AValNo) continue;
474 LiveInterval::Ranges::iterator BI =
475 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
476 if (BI != IntB.ranges.begin())
478 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
479 if (BI->valno == BValNo)
481 if (BI->start <= AI->start && BI->end > AI->start)
483 if (BI->start > AI->start && BI->start < AI->end)
490 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
491 /// IntA being the source and IntB being the dest, thus this defines a value
492 /// number in IntB. If the source value number (in IntA) is defined by a
493 /// commutable instruction and its other operand is coalesced to the copy dest
494 /// register, see if we can transform the copy into a noop by commuting the
495 /// definition. For example,
497 /// A3 = op A2 B0<kill>
499 /// B1 = A3 <- this copy
501 /// = op A3 <- more uses
505 /// B2 = op B0 A2<kill>
507 /// B1 = B2 <- now an identify copy
509 /// = op B2 <- more uses
511 /// This returns true if an interval was modified.
513 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(const CoalescerPair &CP,
514 MachineInstr *CopyMI) {
515 // FIXME: For now, only eliminate the copy by commuting its def when the
516 // source register is a virtual register. We want to guard against cases
517 // where the copy is a back edge copy and commuting the def lengthen the
518 // live interval of the source register to the entire loop.
519 if (CP.isPhys() && CP.isFlipped())
522 // Bail if there is no dst interval.
523 if (!li_->hasInterval(CP.getDstReg()))
526 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
529 li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
531 li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
533 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
534 // the example above.
535 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
536 if (!BValNo || !BValNo->isDefByCopy())
539 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
541 // AValNo is the value number in A that defines the copy, A3 in the example.
542 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getUseIndex());
543 assert(AValNo && "COPY source not live");
545 // If other defs can reach uses of this def, then it's not safe to perform
547 if (AValNo->isPHIDef() || AValNo->isUnused() || AValNo->hasPHIKill())
549 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
552 const TargetInstrDesc &TID = DefMI->getDesc();
553 if (!TID.isCommutable())
555 // If DefMI is a two-address instruction then commuting it will change the
556 // destination register.
557 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
558 assert(DefIdx != -1);
560 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
562 unsigned Op1, Op2, NewDstIdx;
563 if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
567 else if (Op2 == UseOpIdx)
572 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
573 unsigned NewReg = NewDstMO.getReg();
574 if (NewReg != IntB.reg || !NewDstMO.isKill())
577 // Make sure there are no other definitions of IntB that would reach the
578 // uses which the new definition can reach.
579 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
582 // Abort if the aliases of IntB.reg have values that are not simply the
583 // clobbers from the superreg.
584 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
585 for (const unsigned *AS = tri_->getAliasSet(IntB.reg); *AS; ++AS)
586 if (li_->hasInterval(*AS) &&
587 HasOtherReachingDefs(IntA, li_->getInterval(*AS), AValNo, 0))
590 // If some of the uses of IntA.reg is already coalesced away, return false.
591 // It's not possible to determine whether it's safe to perform the coalescing.
592 for (MachineRegisterInfo::use_nodbg_iterator UI =
593 mri_->use_nodbg_begin(IntA.reg),
594 UE = mri_->use_nodbg_end(); UI != UE; ++UI) {
595 MachineInstr *UseMI = &*UI;
596 SlotIndex UseIdx = li_->getInstructionIndex(UseMI);
597 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
598 if (ULR == IntA.end())
600 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
604 DEBUG(dbgs() << "\tRemoveCopyByCommutingDef: " << AValNo->def << '\t'
607 // At this point we have decided that it is legal to do this
608 // transformation. Start by commuting the instruction.
609 MachineBasicBlock *MBB = DefMI->getParent();
610 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
613 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
614 TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
615 !mri_->constrainRegClass(IntB.reg, mri_->getRegClass(IntA.reg)))
617 if (NewMI != DefMI) {
618 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
619 MBB->insert(DefMI, NewMI);
622 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
623 NewMI->getOperand(OpIdx).setIsKill();
625 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
634 // Update uses of IntA of the specific Val# with IntB.
635 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
636 UE = mri_->use_end(); UI != UE;) {
637 MachineOperand &UseMO = UI.getOperand();
638 MachineInstr *UseMI = &*UI;
640 if (JoinedCopies.count(UseMI))
642 if (UseMI->isDebugValue()) {
643 // FIXME These don't have an instruction index. Not clear we have enough
644 // info to decide whether to do this replacement or not. For now do it.
645 UseMO.setReg(NewReg);
648 SlotIndex UseIdx = li_->getInstructionIndex(UseMI).getUseIndex();
649 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
650 if (ULR == IntA.end() || ULR->valno != AValNo)
652 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
653 UseMO.substPhysReg(NewReg, *tri_);
655 UseMO.setReg(NewReg);
658 if (!UseMI->isCopy())
660 if (UseMI->getOperand(0).getReg() != IntB.reg ||
661 UseMI->getOperand(0).getSubReg())
664 // This copy will become a noop. If it's defining a new val#, merge it into
666 SlotIndex DefIdx = UseIdx.getDefIndex();
667 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
670 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
671 assert(DVNI->def == DefIdx);
672 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
676 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
678 VNInfo *ValNo = BValNo;
679 ValNo->def = AValNo->def;
681 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
683 if (AI->valno != AValNo) continue;
684 IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
686 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
688 IntA.removeValNo(AValNo);
689 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
694 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
695 /// computation, replace the copy by rematerialize the definition.
696 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
700 MachineInstr *CopyMI) {
701 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getUseIndex();
702 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
703 assert(SrcLR != SrcInt.end() && "Live range not found!");
704 VNInfo *ValNo = SrcLR->valno;
705 // If other defs can reach uses of this def, then it's not safe to perform
707 if (ValNo->isPHIDef() || ValNo->isUnused() || ValNo->hasPHIKill())
709 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
712 assert(DefMI && "Defining instruction disappeared");
713 const TargetInstrDesc &TID = DefMI->getDesc();
714 if (!TID.isAsCheapAsAMove())
716 if (!tii_->isTriviallyReMaterializable(DefMI, AA))
718 bool SawStore = false;
719 if (!DefMI->isSafeToMove(tii_, AA, SawStore))
721 if (TID.getNumDefs() != 1)
723 if (!DefMI->isImplicitDef()) {
724 // Make sure the copy destination register class fits the instruction
725 // definition register class. The mismatch can happen as a result of earlier
726 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
727 const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
728 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
729 if (mri_->getRegClass(DstReg) != RC)
731 } else if (!RC->contains(DstReg))
735 // If destination register has a sub-register index on it, make sure it
736 // matches the instruction register class.
738 const TargetInstrDesc &TID = DefMI->getDesc();
739 if (TID.getNumDefs() != 1)
741 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
742 const TargetRegisterClass *DstSubRC =
743 DstRC->getSubRegisterRegClass(DstSubIdx);
744 const TargetRegisterClass *DefRC = TID.OpInfo[0].getRegClass(tri_);
747 else if (DefRC != DstSubRC)
751 RemoveCopyFlag(DstReg, CopyMI);
753 MachineBasicBlock *MBB = CopyMI->getParent();
754 MachineBasicBlock::iterator MII =
755 llvm::next(MachineBasicBlock::iterator(CopyMI));
756 tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI, *tri_);
757 MachineInstr *NewMI = prior(MII);
759 // CopyMI may have implicit operands, transfer them over to the newly
760 // rematerialized instruction. And update implicit def interval valnos.
761 for (unsigned i = CopyMI->getDesc().getNumOperands(),
762 e = CopyMI->getNumOperands(); i != e; ++i) {
763 MachineOperand &MO = CopyMI->getOperand(i);
764 if (MO.isReg() && MO.isImplicit())
765 NewMI->addOperand(MO);
767 RemoveCopyFlag(MO.getReg(), CopyMI);
770 NewMI->copyImplicitOps(CopyMI);
771 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
772 CopyMI->eraseFromParent();
773 ReMatCopies.insert(CopyMI);
774 ReMatDefs.insert(DefMI);
775 DEBUG(dbgs() << "Remat: " << *NewMI);
778 // The source interval can become smaller because we removed a use.
780 li_->shrinkToUses(&SrcInt);
785 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
786 /// update the subregister number if it is not zero. If DstReg is a
787 /// physical register and the existing subregister number of the def / use
788 /// being updated is not zero, make sure to set it to the correct physical
791 SimpleRegisterCoalescing::UpdateRegDefsUses(const CoalescerPair &CP) {
792 bool DstIsPhys = CP.isPhys();
793 unsigned SrcReg = CP.getSrcReg();
794 unsigned DstReg = CP.getDstReg();
795 unsigned SubIdx = CP.getSubIdx();
797 // Update LiveDebugVariables.
798 ldv_->renameRegister(SrcReg, DstReg, SubIdx);
800 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg);
801 MachineInstr *UseMI = I.skipInstruction();) {
802 // A PhysReg copy that won't be coalesced can perhaps be rematerialized
805 if (UseMI->isCopy() &&
806 !UseMI->getOperand(1).getSubReg() &&
807 !UseMI->getOperand(0).getSubReg() &&
808 UseMI->getOperand(1).getReg() == SrcReg &&
809 UseMI->getOperand(0).getReg() != SrcReg &&
810 UseMI->getOperand(0).getReg() != DstReg &&
811 !JoinedCopies.count(UseMI) &&
812 ReMaterializeTrivialDef(li_->getInterval(SrcReg), false,
813 UseMI->getOperand(0).getReg(), 0, UseMI))
817 SmallVector<unsigned,8> Ops;
819 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
820 bool Kills = false, Deads = false;
822 // Replace SrcReg with DstReg in all UseMI operands.
823 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
824 MachineOperand &MO = UseMI->getOperand(Ops[i]);
825 Kills |= MO.isKill();
826 Deads |= MO.isDead();
829 MO.substPhysReg(DstReg, *tri_);
831 MO.substVirtReg(DstReg, SubIdx, *tri_);
834 // This instruction is a copy that will be removed.
835 if (JoinedCopies.count(UseMI))
839 // If UseMI was a simple SrcReg def, make sure we didn't turn it into a
840 // read-modify-write of DstReg.
842 UseMI->addRegisterDead(DstReg, tri_);
843 else if (!Reads && Writes)
844 UseMI->addRegisterDefined(DstReg, tri_);
846 // Kill flags apply to the whole physical register.
847 if (DstIsPhys && Kills)
848 UseMI->addRegisterKilled(DstReg, tri_);
852 dbgs() << "\t\tupdated: ";
853 if (!UseMI->isDebugValue())
854 dbgs() << li_->getInstructionIndex(UseMI) << "\t";
860 /// removeIntervalIfEmpty - Check if the live interval of a physical register
861 /// is empty, if so remove it and also remove the empty intervals of its
862 /// sub-registers. Return true if live interval is removed.
863 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
864 const TargetRegisterInfo *tri_) {
866 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
867 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
868 if (!li_->hasInterval(*SR))
870 LiveInterval &sli = li_->getInterval(*SR);
872 li_->removeInterval(*SR);
874 li_->removeInterval(li.reg);
880 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
881 /// the val# it defines. If the live interval becomes empty, remove it as well.
882 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
883 MachineInstr *DefMI) {
884 SlotIndex DefIdx = li_->getInstructionIndex(DefMI).getDefIndex();
885 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
886 if (DefIdx != MLR->valno->def)
888 li.removeValNo(MLR->valno);
889 return removeIntervalIfEmpty(li, li_, tri_);
892 void SimpleRegisterCoalescing::RemoveCopyFlag(unsigned DstReg,
893 const MachineInstr *CopyMI) {
894 SlotIndex DefIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
895 if (li_->hasInterval(DstReg)) {
896 LiveInterval &LI = li_->getInterval(DstReg);
897 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
898 if (LR->valno->def == DefIdx)
899 LR->valno->setCopy(0);
901 if (!TargetRegisterInfo::isPhysicalRegister(DstReg))
903 for (const unsigned* AS = tri_->getAliasSet(DstReg); *AS; ++AS) {
904 if (!li_->hasInterval(*AS))
906 LiveInterval &LI = li_->getInterval(*AS);
907 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
908 if (LR->valno->def == DefIdx)
909 LR->valno->setCopy(0);
913 /// shouldJoinPhys - Return true if a copy involving a physreg should be joined.
914 /// We need to be careful about coalescing a source physical register with a
915 /// virtual register. Once the coalescing is done, it cannot be broken and these
916 /// are not spillable! If the destination interval uses are far away, think
917 /// twice about coalescing them!
918 bool SimpleRegisterCoalescing::shouldJoinPhys(CoalescerPair &CP) {
919 bool Allocatable = li_->isAllocatable(CP.getDstReg());
920 LiveInterval &JoinVInt = li_->getInterval(CP.getSrcReg());
922 /// Always join simple intervals that are defined by a single copy from a
923 /// reserved register. This doesn't increase register pressure, so it is
924 /// always beneficial.
925 if (!Allocatable && CP.isFlipped() && JoinVInt.containsOneValue())
928 if (!EnablePhysicalJoin) {
929 DEBUG(dbgs() << "\tPhysreg joins disabled.\n");
933 // Only coalesce to allocatable physreg, we don't want to risk modifying
934 // reserved registers.
936 DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n");
937 return false; // Not coalescable.
940 // Don't join with physregs that have a ridiculous number of live
941 // ranges. The data structure performance is really bad when that
943 if (li_->hasInterval(CP.getDstReg()) &&
944 li_->getInterval(CP.getDstReg()).ranges.size() > 1000) {
947 << "\tPhysical register live interval too complicated, abort!\n");
951 // FIXME: Why are we skipping this test for partial copies?
952 // CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
953 if (!CP.isPartial()) {
954 const TargetRegisterClass *RC = mri_->getRegClass(CP.getSrcReg());
955 unsigned Threshold = RegClassInfo.getNumAllocatableRegs(RC) * 2;
956 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
957 if (Length > Threshold) {
959 DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
966 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
967 /// two virtual registers from different register classes.
969 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned SrcReg,
971 const TargetRegisterClass *SrcRC,
972 const TargetRegisterClass *DstRC,
973 const TargetRegisterClass *NewRC) {
974 unsigned NewRCCount = RegClassInfo.getNumAllocatableRegs(NewRC);
975 // This heuristics is good enough in practice, but it's obviously not *right*.
976 // 4 is a magic number that works well enough for x86, ARM, etc. It filter
977 // out all but the most restrictive register classes.
978 if (NewRCCount > 4 ||
979 // Early exit if the function is fairly small, coalesce aggressively if
980 // that's the case. For really special register classes with 3 or
981 // fewer registers, be a bit more careful.
982 (li_->getFuncInstructionCount() / NewRCCount) < 8)
984 LiveInterval &SrcInt = li_->getInterval(SrcReg);
985 LiveInterval &DstInt = li_->getInterval(DstReg);
986 unsigned SrcSize = li_->getApproximateInstructionCount(SrcInt);
987 unsigned DstSize = li_->getApproximateInstructionCount(DstInt);
989 // Coalesce aggressively if the intervals are small compared to the number of
990 // registers in the new class. The number 4 is fairly arbitrary, chosen to be
991 // less aggressive than the 8 used for the whole function size.
992 const unsigned ThresSize = 4 * NewRCCount;
993 if (SrcSize <= ThresSize && DstSize <= ThresSize)
996 // Estimate *register use density*. If it doubles or more, abort.
997 unsigned SrcUses = std::distance(mri_->use_nodbg_begin(SrcReg),
998 mri_->use_nodbg_end());
999 unsigned DstUses = std::distance(mri_->use_nodbg_begin(DstReg),
1000 mri_->use_nodbg_end());
1001 unsigned NewUses = SrcUses + DstUses;
1002 unsigned NewSize = SrcSize + DstSize;
1003 if (SrcRC != NewRC && SrcSize > ThresSize) {
1004 unsigned SrcRCCount = RegClassInfo.getNumAllocatableRegs(SrcRC);
1005 if (NewUses*SrcSize*SrcRCCount > 2*SrcUses*NewSize*NewRCCount)
1008 if (DstRC != NewRC && DstSize > ThresSize) {
1009 unsigned DstRCCount = RegClassInfo.getNumAllocatableRegs(DstRC);
1010 if (NewUses*DstSize*DstRCCount > 2*DstUses*NewSize*NewRCCount)
1017 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1018 /// which are the src/dst of the copy instruction CopyMI. This returns true
1019 /// if the copy was successfully coalesced away. If it is not currently
1020 /// possible to coalesce this interval, but it may be possible if other
1021 /// things get coalesced, then it returns true by reference in 'Again'.
1022 bool SimpleRegisterCoalescing::JoinCopy(MachineInstr *CopyMI, bool &Again) {
1025 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1026 return false; // Already done.
1028 DEBUG(dbgs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1030 CoalescerPair CP(*tii_, *tri_);
1031 if (!CP.setRegisters(CopyMI)) {
1032 DEBUG(dbgs() << "\tNot coalescable.\n");
1036 // If they are already joined we continue.
1037 if (CP.getSrcReg() == CP.getDstReg()) {
1038 markAsJoined(CopyMI);
1039 DEBUG(dbgs() << "\tCopy already coalesced.\n");
1040 return false; // Not coalescable.
1043 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), tri_)
1044 << " with " << PrintReg(CP.getDstReg(), tri_, CP.getSubIdx())
1047 // Enforce policies.
1049 if (!shouldJoinPhys(CP)) {
1050 // Before giving up coalescing, if definition of source is defined by
1051 // trivial computation, try rematerializing it.
1052 if (!CP.isFlipped() &&
1053 ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()), true,
1054 CP.getDstReg(), 0, CopyMI))
1059 // Avoid constraining virtual register regclass too much.
1060 if (CP.isCrossClass()) {
1061 DEBUG(dbgs() << "\tCross-class to " << CP.getNewRC()->getName() << ".\n");
1062 if (DisableCrossClassJoin) {
1063 DEBUG(dbgs() << "\tCross-class joins disabled.\n");
1066 if (!isWinToJoinCrossClass(CP.getSrcReg(), CP.getDstReg(),
1067 mri_->getRegClass(CP.getSrcReg()),
1068 mri_->getRegClass(CP.getDstReg()),
1070 DEBUG(dbgs() << "\tAvoid coalescing to constrained register class.\n");
1071 Again = true; // May be possible to coalesce later.
1076 // When possible, let DstReg be the larger interval.
1077 if (!CP.getSubIdx() && li_->getInterval(CP.getSrcReg()).ranges.size() >
1078 li_->getInterval(CP.getDstReg()).ranges.size())
1082 // Okay, attempt to join these two intervals. On failure, this returns false.
1083 // Otherwise, if one of the intervals being joined is a physreg, this method
1084 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1085 // been modified, so we can use this information below to update aliases.
1086 if (!JoinIntervals(CP)) {
1087 // Coalescing failed.
1089 // If definition of source is defined by trivial computation, try
1090 // rematerializing it.
1091 if (!CP.isFlipped() &&
1092 ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()), true,
1093 CP.getDstReg(), 0, CopyMI))
1096 // If we can eliminate the copy without merging the live ranges, do so now.
1097 if (!CP.isPartial()) {
1098 if (AdjustCopiesBackFrom(CP, CopyMI) ||
1099 RemoveCopyByCommutingDef(CP, CopyMI)) {
1100 markAsJoined(CopyMI);
1101 DEBUG(dbgs() << "\tTrivial!\n");
1106 // Otherwise, we are unable to join the intervals.
1107 DEBUG(dbgs() << "\tInterference!\n");
1108 Again = true; // May be possible to coalesce later.
1112 // Coalescing to a virtual register that is of a sub-register class of the
1113 // other. Make sure the resulting register is set to the right register class.
1114 if (CP.isCrossClass()) {
1116 mri_->setRegClass(CP.getDstReg(), CP.getNewRC());
1119 // Remember to delete the copy instruction.
1120 markAsJoined(CopyMI);
1122 UpdateRegDefsUses(CP);
1124 // If we have extended the live range of a physical register, make sure we
1125 // update live-in lists as well.
1127 SmallVector<MachineBasicBlock*, 16> BlockSeq;
1128 // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
1129 // ranges for this, and they are preserved.
1130 LiveInterval &SrcInt = li_->getInterval(CP.getSrcReg());
1131 for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
1133 li_->findLiveInMBBs(I->start, I->end, BlockSeq);
1134 for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1135 MachineBasicBlock &block = *BlockSeq[idx];
1136 if (!block.isLiveIn(CP.getDstReg()))
1137 block.addLiveIn(CP.getDstReg());
1143 // SrcReg is guarateed to be the register whose live interval that is
1145 li_->removeInterval(CP.getSrcReg());
1147 // Update regalloc hint.
1148 tri_->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *mf_);
1151 LiveInterval &DstInt = li_->getInterval(CP.getDstReg());
1152 dbgs() << "\tJoined. Result = ";
1153 DstInt.print(dbgs(), tri_);
1161 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1162 /// compute what the resultant value numbers for each value in the input two
1163 /// ranges will be. This is complicated by copies between the two which can
1164 /// and will commonly cause multiple value numbers to be merged into one.
1166 /// VN is the value number that we're trying to resolve. InstDefiningValue
1167 /// keeps track of the new InstDefiningValue assignment for the result
1168 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1169 /// whether a value in this or other is a copy from the opposite set.
1170 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1171 /// already been assigned.
1173 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1174 /// contains the value number the copy is from.
1176 static unsigned ComputeUltimateVN(VNInfo *VNI,
1177 SmallVector<VNInfo*, 16> &NewVNInfo,
1178 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1179 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1180 SmallVector<int, 16> &ThisValNoAssignments,
1181 SmallVector<int, 16> &OtherValNoAssignments) {
1182 unsigned VN = VNI->id;
1184 // If the VN has already been computed, just return it.
1185 if (ThisValNoAssignments[VN] >= 0)
1186 return ThisValNoAssignments[VN];
1187 assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1189 // If this val is not a copy from the other val, then it must be a new value
1190 // number in the destination.
1191 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1192 if (I == ThisFromOther.end()) {
1193 NewVNInfo.push_back(VNI);
1194 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1196 VNInfo *OtherValNo = I->second;
1198 // Otherwise, this *is* a copy from the RHS. If the other side has already
1199 // been computed, return it.
1200 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1201 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1203 // Mark this value number as currently being computed, then ask what the
1204 // ultimate value # of the other value is.
1205 ThisValNoAssignments[VN] = -2;
1206 unsigned UltimateVN =
1207 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1208 OtherValNoAssignments, ThisValNoAssignments);
1209 return ThisValNoAssignments[VN] = UltimateVN;
1212 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1214 bool SimpleRegisterCoalescing::JoinIntervals(CoalescerPair &CP) {
1215 LiveInterval &RHS = li_->getInterval(CP.getSrcReg());
1216 DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), tri_); dbgs() << "\n"; });
1218 // If a live interval is a physical register, check for interference with any
1219 // aliases. The interference check implemented here is a bit more conservative
1220 // than the full interfeence check below. We allow overlapping live ranges
1221 // only when one is a copy of the other.
1223 for (const unsigned *AS = tri_->getAliasSet(CP.getDstReg()); *AS; ++AS){
1224 if (!li_->hasInterval(*AS))
1226 const LiveInterval &LHS = li_->getInterval(*AS);
1227 LiveInterval::const_iterator LI = LHS.begin();
1228 for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1230 LI = std::lower_bound(LI, LHS.end(), RI->start);
1231 // Does LHS have an overlapping live range starting before RI?
1232 if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1233 (RI->start != RI->valno->def ||
1234 !CP.isCoalescable(li_->getInstructionFromIndex(RI->start)))) {
1236 dbgs() << "\t\tInterference from alias: ";
1237 LHS.print(dbgs(), tri_);
1238 dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1243 // Check that LHS ranges beginning in this range are copies.
1244 for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1245 if (LI->start != LI->valno->def ||
1246 !CP.isCoalescable(li_->getInstructionFromIndex(LI->start))) {
1248 dbgs() << "\t\tInterference from alias: ";
1249 LHS.print(dbgs(), tri_);
1250 dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1259 // Compute the final value assignment, assuming that the live ranges can be
1261 SmallVector<int, 16> LHSValNoAssignments;
1262 SmallVector<int, 16> RHSValNoAssignments;
1263 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1264 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1265 SmallVector<VNInfo*, 16> NewVNInfo;
1267 LiveInterval &LHS = li_->getOrCreateInterval(CP.getDstReg());
1268 DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), tri_); dbgs() << "\n"; });
1270 // Loop over the value numbers of the LHS, seeing if any are defined from
1272 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1275 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy?
1278 // Never join with a register that has EarlyClobber redefs.
1279 if (VNI->hasRedefByEC())
1282 // DstReg is known to be a register in the LHS interval. If the src is
1283 // from the RHS interval, we can use its value #.
1284 if (!CP.isCoalescable(VNI->getCopy()))
1287 // Figure out the value # from the RHS.
1288 LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1289 // The copy could be to an aliased physreg.
1291 LHSValsDefinedFromRHS[VNI] = lr->valno;
1294 // Loop over the value numbers of the RHS, seeing if any are defined from
1296 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1299 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy?
1302 // Never join with a register that has EarlyClobber redefs.
1303 if (VNI->hasRedefByEC())
1306 // DstReg is known to be a register in the RHS interval. If the src is
1307 // from the LHS interval, we can use its value #.
1308 if (!CP.isCoalescable(VNI->getCopy()))
1311 // Figure out the value # from the LHS.
1312 LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1313 // The copy could be to an aliased physreg.
1315 RHSValsDefinedFromLHS[VNI] = lr->valno;
1318 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1319 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1320 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1322 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1325 unsigned VN = VNI->id;
1326 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1328 ComputeUltimateVN(VNI, NewVNInfo,
1329 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1330 LHSValNoAssignments, RHSValNoAssignments);
1332 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1335 unsigned VN = VNI->id;
1336 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1338 // If this value number isn't a copy from the LHS, it's a new number.
1339 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1340 NewVNInfo.push_back(VNI);
1341 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1345 ComputeUltimateVN(VNI, NewVNInfo,
1346 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1347 RHSValNoAssignments, LHSValNoAssignments);
1350 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1351 // interval lists to see if these intervals are coalescable.
1352 LiveInterval::const_iterator I = LHS.begin();
1353 LiveInterval::const_iterator IE = LHS.end();
1354 LiveInterval::const_iterator J = RHS.begin();
1355 LiveInterval::const_iterator JE = RHS.end();
1357 // Skip ahead until the first place of potential sharing.
1358 if (I != IE && J != JE) {
1359 if (I->start < J->start) {
1360 I = std::upper_bound(I, IE, J->start);
1361 if (I != LHS.begin()) --I;
1362 } else if (J->start < I->start) {
1363 J = std::upper_bound(J, JE, I->start);
1364 if (J != RHS.begin()) --J;
1368 while (I != IE && J != JE) {
1369 // Determine if these two live ranges overlap.
1371 if (I->start < J->start) {
1372 Overlaps = I->end > J->start;
1374 Overlaps = J->end > I->start;
1377 // If so, check value # info to determine if they are really different.
1379 // If the live range overlap will map to the same value number in the
1380 // result liverange, we can still coalesce them. If not, we can't.
1381 if (LHSValNoAssignments[I->valno->id] !=
1382 RHSValNoAssignments[J->valno->id])
1384 // If it's re-defined by an early clobber somewhere in the live range,
1385 // then conservatively abort coalescing.
1386 if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
1390 if (I->end < J->end)
1396 // Update kill info. Some live ranges are extended due to copy coalescing.
1397 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1398 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1399 VNInfo *VNI = I->first;
1400 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1401 if (VNI->hasPHIKill())
1402 NewVNInfo[LHSValID]->setHasPHIKill(true);
1405 // Update kill info. Some live ranges are extended due to copy coalescing.
1406 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1407 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1408 VNInfo *VNI = I->first;
1409 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1410 if (VNI->hasPHIKill())
1411 NewVNInfo[RHSValID]->setHasPHIKill(true);
1414 if (LHSValNoAssignments.empty())
1415 LHSValNoAssignments.push_back(-1);
1416 if (RHSValNoAssignments.empty())
1417 RHSValNoAssignments.push_back(-1);
1419 // If we get here, we know that we can coalesce the live ranges. Ask the
1420 // intervals to coalesce themselves now.
1421 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1427 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1428 // depth of the basic block (the unsigned), and then on the MBB number.
1429 struct DepthMBBCompare {
1430 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1431 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1432 // Deeper loops first
1433 if (LHS.first != RHS.first)
1434 return LHS.first > RHS.first;
1436 // Prefer blocks that are more connected in the CFG. This takes care of
1437 // the most difficult copies first while intervals are short.
1438 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1439 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1443 // As a last resort, sort by block number.
1444 return LHS.second->getNumber() < RHS.second->getNumber();
1449 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1450 std::vector<MachineInstr*> &TryAgain) {
1451 DEBUG(dbgs() << MBB->getName() << ":\n");
1453 SmallVector<MachineInstr*, 8> VirtCopies;
1454 SmallVector<MachineInstr*, 8> PhysCopies;
1455 SmallVector<MachineInstr*, 8> ImpDefCopies;
1456 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1458 MachineInstr *Inst = MII++;
1460 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1461 unsigned SrcReg, DstReg;
1462 if (Inst->isCopy()) {
1463 DstReg = Inst->getOperand(0).getReg();
1464 SrcReg = Inst->getOperand(1).getReg();
1465 } else if (Inst->isSubregToReg()) {
1466 DstReg = Inst->getOperand(0).getReg();
1467 SrcReg = Inst->getOperand(2).getReg();
1471 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1472 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1473 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1474 ImpDefCopies.push_back(Inst);
1475 else if (SrcIsPhys || DstIsPhys)
1476 PhysCopies.push_back(Inst);
1478 VirtCopies.push_back(Inst);
1481 // Try coalescing implicit copies and insert_subreg <undef> first,
1482 // followed by copies to / from physical registers, then finally copies
1483 // from virtual registers to virtual registers.
1484 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1485 MachineInstr *TheCopy = ImpDefCopies[i];
1487 if (!JoinCopy(TheCopy, Again))
1489 TryAgain.push_back(TheCopy);
1491 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1492 MachineInstr *TheCopy = PhysCopies[i];
1494 if (!JoinCopy(TheCopy, Again))
1496 TryAgain.push_back(TheCopy);
1498 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1499 MachineInstr *TheCopy = VirtCopies[i];
1501 if (!JoinCopy(TheCopy, Again))
1503 TryAgain.push_back(TheCopy);
1507 void SimpleRegisterCoalescing::joinIntervals() {
1508 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1510 std::vector<MachineInstr*> TryAgainList;
1511 if (loopInfo->empty()) {
1512 // If there are no loops in the function, join intervals in function order.
1513 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1515 CopyCoalesceInMBB(I, TryAgainList);
1517 // Otherwise, join intervals in inner loops before other intervals.
1518 // Unfortunately we can't just iterate over loop hierarchy here because
1519 // there may be more MBB's than BB's. Collect MBB's for sorting.
1521 // Join intervals in the function prolog first. We want to join physical
1522 // registers with virtual registers before the intervals got too long.
1523 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1524 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1525 MachineBasicBlock *MBB = I;
1526 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1529 // Sort by loop depth.
1530 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1532 // Finally, join intervals in loop nest order.
1533 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1534 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1537 // Joining intervals can allow other intervals to be joined. Iteratively join
1538 // until we make no progress.
1539 bool ProgressMade = true;
1540 while (ProgressMade) {
1541 ProgressMade = false;
1543 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1544 MachineInstr *&TheCopy = TryAgainList[i];
1549 bool Success = JoinCopy(TheCopy, Again);
1550 if (Success || !Again) {
1551 TheCopy= 0; // Mark this one as done.
1552 ProgressMade = true;
1558 void SimpleRegisterCoalescing::releaseMemory() {
1559 JoinedCopies.clear();
1560 ReMatCopies.clear();
1564 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1566 mri_ = &fn.getRegInfo();
1567 tm_ = &fn.getTarget();
1568 tri_ = tm_->getRegisterInfo();
1569 tii_ = tm_->getInstrInfo();
1570 li_ = &getAnalysis<LiveIntervals>();
1571 ldv_ = &getAnalysis<LiveDebugVariables>();
1572 AA = &getAnalysis<AliasAnalysis>();
1573 loopInfo = &getAnalysis<MachineLoopInfo>();
1575 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1576 << "********** Function: "
1577 << ((Value*)mf_->getFunction())->getName() << '\n');
1579 if (VerifyCoalescing)
1580 mf_->verify(this, "Before register coalescing");
1582 RegClassInfo.runOnMachineFunction(fn);
1584 // Join (coalesce) intervals if requested.
1585 if (EnableJoining) {
1588 dbgs() << "********** INTERVALS POST JOINING **********\n";
1589 for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
1591 I->second->print(dbgs(), tri_);
1597 // Perform a final pass over the instructions and compute spill weights
1598 // and remove identity moves.
1599 SmallVector<unsigned, 4> DeadDefs;
1600 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1601 mbbi != mbbe; ++mbbi) {
1602 MachineBasicBlock* mbb = mbbi;
1603 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1605 MachineInstr *MI = mii;
1606 if (JoinedCopies.count(MI)) {
1607 // Delete all coalesced copies.
1608 bool DoDelete = true;
1609 assert(MI->isCopyLike() && "Unrecognized copy instruction");
1610 unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1611 if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1612 MI->getNumOperands() > 2)
1613 // Do not delete extract_subreg, insert_subreg of physical
1614 // registers unless the definition is dead. e.g.
1615 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1616 // or else the scavenger may complain. LowerSubregs will
1617 // delete them later.
1620 if (MI->allDefsAreDead()) {
1621 if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1622 li_->hasInterval(SrcReg))
1623 li_->shrinkToUses(&li_->getInterval(SrcReg));
1627 // We need the instruction to adjust liveness, so make it a KILL.
1628 if (MI->isSubregToReg()) {
1629 MI->RemoveOperand(3);
1630 MI->RemoveOperand(1);
1632 MI->setDesc(tii_->get(TargetOpcode::KILL));
1633 mii = llvm::next(mii);
1635 li_->RemoveMachineInstrFromMaps(MI);
1636 mii = mbbi->erase(mii);
1642 // Now check if this is a remat'ed def instruction which is now dead.
1643 if (ReMatDefs.count(MI)) {
1645 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1646 const MachineOperand &MO = MI->getOperand(i);
1649 unsigned Reg = MO.getReg();
1652 if (TargetRegisterInfo::isVirtualRegister(Reg))
1653 DeadDefs.push_back(Reg);
1656 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1657 !mri_->use_nodbg_empty(Reg)) {
1663 while (!DeadDefs.empty()) {
1664 unsigned DeadDef = DeadDefs.back();
1665 DeadDefs.pop_back();
1666 RemoveDeadDef(li_->getInterval(DeadDef), MI);
1668 li_->RemoveMachineInstrFromMaps(mii);
1669 mii = mbbi->erase(mii);
1677 // Check for now unnecessary kill flags.
1678 if (li_->isNotInMIMap(MI)) continue;
1679 SlotIndex DefIdx = li_->getInstructionIndex(MI).getDefIndex();
1680 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1681 MachineOperand &MO = MI->getOperand(i);
1682 if (!MO.isReg() || !MO.isKill()) continue;
1683 unsigned reg = MO.getReg();
1684 if (!reg || !li_->hasInterval(reg)) continue;
1685 if (!li_->getInterval(reg).killedAt(DefIdx)) {
1686 MO.setIsKill(false);
1689 // When leaving a kill flag on a physreg, check if any subregs should
1691 if (!TargetRegisterInfo::isPhysicalRegister(reg))
1693 for (const unsigned *SR = tri_->getSubRegisters(reg);
1694 unsigned S = *SR; ++SR)
1695 if (li_->hasInterval(S) && li_->getInterval(S).liveAt(DefIdx))
1696 MI->addRegisterDefined(S, tri_);
1702 DEBUG(ldv_->dump());
1703 if (VerifyCoalescing)
1704 mf_->verify(this, "After register coalescing");
1708 /// print - Implement the dump method.
1709 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
1713 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1714 return new SimpleRegisterCoalescing();
1717 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1718 DEFINING_FILE_FOR(SimpleRegisterCoalescing)