1 //===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a simple register coalescing pass that attempts to
11 // aggressively coalesce every register copy that it can.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regcoalescing"
16 #include "SimpleRegisterCoalescing.h"
17 #include "VirtRegMap.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/Value.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/RegisterCoalescer.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ADT/SmallSet.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/STLExtras.h"
41 STATISTIC(numJoins , "Number of interval joins performed");
42 STATISTIC(numCrossRCs , "Number of cross class joins performed");
43 STATISTIC(numCommutes , "Number of instruction commuting performed");
44 STATISTIC(numExtends , "Number of copies extended");
45 STATISTIC(NumReMats , "Number of instructions re-materialized");
46 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
47 STATISTIC(numAborts , "Number of times interval joining aborted");
48 STATISTIC(numDeadValNo, "Number of valno def marked dead");
50 char SimpleRegisterCoalescing::ID = 0;
52 EnableJoining("join-liveintervals",
53 cl::desc("Coalesce copies (default=true)"),
57 DisableCrossClassJoin("disable-cross-class-join",
58 cl::desc("Avoid coalescing cross register class copies"),
59 cl::init(false), cl::Hidden);
62 PhysJoinTweak("tweak-phys-join-heuristics",
63 cl::desc("Tweak heuristics for joining phys reg with vr"),
64 cl::init(false), cl::Hidden);
66 static RegisterPass<SimpleRegisterCoalescing>
67 X("simple-register-coalescing", "Simple Register Coalescing");
69 // Declare that we implement the RegisterCoalescer interface
70 static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
72 const PassInfo *const llvm::SimpleRegisterCoalescingID = &X;
74 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
76 AU.addRequired<AliasAnalysis>();
77 AU.addRequired<LiveIntervals>();
78 AU.addPreserved<LiveIntervals>();
79 AU.addPreserved<SlotIndexes>();
80 AU.addRequired<MachineLoopInfo>();
81 AU.addPreserved<MachineLoopInfo>();
82 AU.addPreservedID(MachineDominatorsID);
84 AU.addPreservedID(StrongPHIEliminationID);
86 AU.addPreservedID(PHIEliminationID);
87 AU.addPreservedID(TwoAddressInstructionPassID);
88 MachineFunctionPass::getAnalysisUsage(AU);
91 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
92 /// being the source and IntB being the dest, thus this defines a value number
93 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
94 /// see if we can merge these two pieces of B into a single value number,
95 /// eliminating a copy. For example:
99 /// B1 = A3 <- this copy
101 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
102 /// value number to be replaced with B0 (which simplifies the B liveinterval).
104 /// This returns true if an interval was modified.
106 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
108 MachineInstr *CopyMI) {
109 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
111 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
112 // the example above.
113 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
114 assert(BLR != IntB.end() && "Live range not found!");
115 VNInfo *BValNo = BLR->valno;
117 // Get the location that B is defined at. Two options: either this value has
118 // an unknown definition point or it is defined at CopyIdx. If unknown, we
120 if (!BValNo->getCopy()) return false;
121 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
123 // AValNo is the value number in A that defines the copy, A3 in the example.
124 SlotIndex CopyUseIdx = CopyIdx.getUseIndex();
125 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
126 assert(ALR != IntA.end() && "Live range not found!");
127 VNInfo *AValNo = ALR->valno;
128 // If it's re-defined by an early clobber somewhere in the live range, then
129 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
131 // 172 %ECX<def> = MOV32rr %reg1039<kill>
132 // 180 INLINEASM <es:subl $5,$1
133 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9,
135 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
136 // 188 %EAX<def> = MOV32rr %EAX<kill>
137 // 196 %ECX<def> = MOV32rr %ECX<kill>
138 // 204 %ECX<def> = MOV32rr %ECX<kill>
139 // 212 %EAX<def> = MOV32rr %EAX<kill>
140 // 220 %EAX<def> = MOV32rr %EAX
141 // 228 %reg1039<def> = MOV32rr %ECX<kill>
142 // The early clobber operand ties ECX input to the ECX def.
144 // The live interval of ECX is represented as this:
145 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
146 // The coalescer has no idea there was a def in the middle of [174,230].
147 if (AValNo->hasRedefByEC())
150 // If AValNo is defined as a copy from IntB, we can potentially process this.
151 // Get the instruction that defines this value number.
152 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
153 if (!SrcReg) return false; // Not defined by a copy.
155 // If the value number is not defined by a copy instruction, ignore it.
157 // If the source register comes from an interval other than IntB, we can't
159 if (SrcReg != IntB.reg) return false;
161 // Get the LiveRange in IntB that this value number starts with.
162 LiveInterval::iterator ValLR =
163 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
164 assert(ValLR != IntB.end() && "Live range not found!");
166 // Make sure that the end of the live range is inside the same block as
168 MachineInstr *ValLREndInst =
169 li_->getInstructionFromIndex(ValLR->end.getPrevSlot());
171 ValLREndInst->getParent() != CopyMI->getParent()) return false;
173 // Okay, we now know that ValLR ends in the same block that the CopyMI
174 // live-range starts. If there are no intervening live ranges between them in
175 // IntB, we can merge them.
176 if (ValLR+1 != BLR) return false;
178 // If a live interval is a physical register, conservatively check if any
179 // of its sub-registers is overlapping the live interval of the virtual
180 // register. If so, do not coalesce.
181 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
182 *tri_->getSubRegisters(IntB.reg)) {
183 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
184 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
186 errs() << "Interfere with sub-register ";
187 li_->getInterval(*SR).print(errs(), tri_);
194 errs() << "\nExtending: ";
195 IntB.print(errs(), tri_);
198 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
199 // We are about to delete CopyMI, so need to remove it as the 'instruction
200 // that defines this value #'. Update the the valnum with the new defining
202 BValNo->def = FillerStart;
205 // Okay, we can merge them. We need to insert a new liverange:
206 // [ValLR.end, BLR.begin) of either value number, then we merge the
207 // two value numbers.
208 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
210 // If the IntB live range is assigned to a physical register, and if that
211 // physreg has sub-registers, update their live intervals as well.
212 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
213 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
214 LiveInterval &SRLI = li_->getInterval(*SR);
215 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
216 SRLI.getNextValue(FillerStart, 0, true,
217 li_->getVNInfoAllocator())));
221 // Okay, merge "B1" into the same value number as "B0".
222 if (BValNo != ValLR->valno) {
223 IntB.addKills(ValLR->valno, BValNo->kills);
224 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
227 errs() << " result = ";
228 IntB.print(errs(), tri_);
232 // If the source instruction was killing the source register before the
233 // merge, unset the isKill marker given the live range has been extended.
234 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
236 ValLREndInst->getOperand(UIdx).setIsKill(false);
237 ValLR->valno->removeKill(FillerStart);
240 // If the copy instruction was killing the destination register before the
241 // merge, find the last use and trim the live range. That will also add the
243 if (CopyMI->killsRegister(IntA.reg))
244 TrimLiveIntervalToLastUse(CopyUseIdx, CopyMI->getParent(), IntA, ALR);
250 /// HasOtherReachingDefs - Return true if there are definitions of IntB
251 /// other than BValNo val# that can reach uses of AValno val# of IntA.
252 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
256 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
258 if (AI->valno != AValNo) continue;
259 LiveInterval::Ranges::iterator BI =
260 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
261 if (BI != IntB.ranges.begin())
263 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
264 if (BI->valno == BValNo)
266 if (BI->start <= AI->start && BI->end > AI->start)
268 if (BI->start > AI->start && BI->start < AI->end)
276 TransferImplicitOps(MachineInstr *MI, MachineInstr *NewMI) {
277 for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
279 MachineOperand &MO = MI->getOperand(i);
280 if (MO.isReg() && MO.isImplicit())
281 NewMI->addOperand(MO);
285 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
286 /// IntA being the source and IntB being the dest, thus this defines a value
287 /// number in IntB. If the source value number (in IntA) is defined by a
288 /// commutable instruction and its other operand is coalesced to the copy dest
289 /// register, see if we can transform the copy into a noop by commuting the
290 /// definition. For example,
292 /// A3 = op A2 B0<kill>
294 /// B1 = A3 <- this copy
296 /// = op A3 <- more uses
300 /// B2 = op B0 A2<kill>
302 /// B1 = B2 <- now an identify copy
304 /// = op B2 <- more uses
306 /// This returns true if an interval was modified.
308 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
310 MachineInstr *CopyMI) {
312 li_->getInstructionIndex(CopyMI).getDefIndex();
314 // FIXME: For now, only eliminate the copy by commuting its def when the
315 // source register is a virtual register. We want to guard against cases
316 // where the copy is a back edge copy and commuting the def lengthen the
317 // live interval of the source register to the entire loop.
318 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
321 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
322 // the example above.
323 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
324 assert(BLR != IntB.end() && "Live range not found!");
325 VNInfo *BValNo = BLR->valno;
327 // Get the location that B is defined at. Two options: either this value has
328 // an unknown definition point or it is defined at CopyIdx. If unknown, we
330 if (!BValNo->getCopy()) return false;
331 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
333 // AValNo is the value number in A that defines the copy, A3 in the example.
334 LiveInterval::iterator ALR =
335 IntA.FindLiveRangeContaining(CopyIdx.getUseIndex()); //
337 assert(ALR != IntA.end() && "Live range not found!");
338 VNInfo *AValNo = ALR->valno;
339 // If other defs can reach uses of this def, then it's not safe to perform
340 // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
342 if (AValNo->isPHIDef() || !AValNo->isDefAccurate() ||
343 AValNo->isUnused() || AValNo->hasPHIKill())
345 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
346 const TargetInstrDesc &TID = DefMI->getDesc();
347 if (!TID.isCommutable())
349 // If DefMI is a two-address instruction then commuting it will change the
350 // destination register.
351 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
352 assert(DefIdx != -1);
354 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
356 unsigned Op1, Op2, NewDstIdx;
357 if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
361 else if (Op2 == UseOpIdx)
366 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
367 unsigned NewReg = NewDstMO.getReg();
368 if (NewReg != IntB.reg || !NewDstMO.isKill())
371 // Make sure there are no other definitions of IntB that would reach the
372 // uses which the new definition can reach.
373 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
376 // If some of the uses of IntA.reg is already coalesced away, return false.
377 // It's not possible to determine whether it's safe to perform the coalescing.
378 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
379 UE = mri_->use_end(); UI != UE; ++UI) {
380 MachineInstr *UseMI = &*UI;
381 SlotIndex UseIdx = li_->getInstructionIndex(UseMI);
382 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
383 if (ULR == IntA.end())
385 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
389 // At this point we have decided that it is legal to do this
390 // transformation. Start by commuting the instruction.
391 MachineBasicBlock *MBB = DefMI->getParent();
392 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
395 if (NewMI != DefMI) {
396 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
397 MBB->insert(DefMI, NewMI);
400 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
401 NewMI->getOperand(OpIdx).setIsKill();
403 bool BHasPHIKill = BValNo->hasPHIKill();
404 SmallVector<VNInfo*, 4> BDeadValNos;
405 VNInfo::KillSet BKills;
406 std::map<SlotIndex, SlotIndex> BExtend;
408 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
417 // then do not add kills of A to the newly created B interval.
418 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
420 BExtend[ALR->end] = BLR->end;
422 // Update uses of IntA of the specific Val# with IntB.
423 bool BHasSubRegs = false;
424 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
425 BHasSubRegs = *tri_->getSubRegisters(IntB.reg);
426 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
427 UE = mri_->use_end(); UI != UE;) {
428 MachineOperand &UseMO = UI.getOperand();
429 MachineInstr *UseMI = &*UI;
431 if (JoinedCopies.count(UseMI))
433 SlotIndex UseIdx = li_->getInstructionIndex(UseMI).getUseIndex();
434 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
435 if (ULR == IntA.end() || ULR->valno != AValNo)
437 UseMO.setReg(NewReg);
440 if (UseMO.isKill()) {
442 UseMO.setIsKill(false);
444 BKills.push_back(UseIdx.getDefIndex());
446 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
447 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
449 if (DstReg == IntB.reg) {
450 // This copy will become a noop. If it's defining a new val#,
451 // remove that val# as well. However this live range is being
452 // extended to the end of the existing live range defined by the copy.
453 SlotIndex DefIdx = UseIdx.getDefIndex();
454 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
455 BHasPHIKill |= DLR->valno->hasPHIKill();
456 assert(DLR->valno->def == DefIdx);
457 BDeadValNos.push_back(DLR->valno);
458 BExtend[DLR->start] = DLR->end;
459 JoinedCopies.insert(UseMI);
460 // If this is a kill but it's going to be removed, the last use
461 // of the same val# is the new kill.
467 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
468 // simply extend BLR if CopyMI doesn't end the range.
470 errs() << "\nExtending: ";
471 IntB.print(errs(), tri_);
474 // Remove val#'s defined by copies that will be coalesced away.
475 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i) {
476 VNInfo *DeadVNI = BDeadValNos[i];
478 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
479 LiveInterval &SRLI = li_->getInterval(*SR);
480 const LiveRange *SRLR = SRLI.getLiveRangeContaining(DeadVNI->def);
481 SRLI.removeValNo(SRLR->valno);
484 IntB.removeValNo(BDeadValNos[i]);
487 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
488 // is updated. Kills are also updated.
489 VNInfo *ValNo = BValNo;
490 ValNo->def = AValNo->def;
492 for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) {
493 if (ValNo->kills[j] != BLR->end)
494 BKills.push_back(ValNo->kills[j]);
496 ValNo->kills.clear();
497 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
499 if (AI->valno != AValNo) continue;
500 SlotIndex End = AI->end;
501 std::map<SlotIndex, SlotIndex>::iterator
502 EI = BExtend.find(End);
503 if (EI != BExtend.end())
505 IntB.addRange(LiveRange(AI->start, End, ValNo));
507 // If the IntB live range is assigned to a physical register, and if that
508 // physreg has sub-registers, update their live intervals as well.
510 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
511 LiveInterval &SRLI = li_->getInterval(*SR);
512 SRLI.MergeInClobberRange(*li_, AI->start, End,
513 li_->getVNInfoAllocator());
517 IntB.addKills(ValNo, BKills);
518 ValNo->setHasPHIKill(BHasPHIKill);
521 errs() << " result = ";
522 IntB.print(errs(), tri_);
524 errs() << "\nShortening: ";
525 IntA.print(errs(), tri_);
528 IntA.removeValNo(AValNo);
531 errs() << " result = ";
532 IntA.print(errs(), tri_);
540 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
541 /// fallthoughs to SuccMBB.
542 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
543 MachineBasicBlock *SuccMBB,
544 const TargetInstrInfo *tii_) {
547 MachineBasicBlock *TBB = 0, *FBB = 0;
548 SmallVector<MachineOperand, 4> Cond;
549 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
550 MBB->isSuccessor(SuccMBB);
553 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
554 /// from a physical register live interval as well as from the live intervals
555 /// of its sub-registers.
556 static void removeRange(LiveInterval &li,
557 SlotIndex Start, SlotIndex End,
558 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
559 li.removeRange(Start, End, true);
560 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
561 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
562 if (!li_->hasInterval(*SR))
564 LiveInterval &sli = li_->getInterval(*SR);
565 SlotIndex RemoveStart = Start;
566 SlotIndex RemoveEnd = Start;
568 while (RemoveEnd != End) {
569 LiveInterval::iterator LR = sli.FindLiveRangeContaining(RemoveStart);
572 RemoveEnd = (LR->end < End) ? LR->end : End;
573 sli.removeRange(RemoveStart, RemoveEnd, true);
574 RemoveStart = RemoveEnd;
580 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
581 /// as the copy instruction, trim the live interval to the last use and return
584 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(SlotIndex CopyIdx,
585 MachineBasicBlock *CopyMBB,
587 const LiveRange *LR) {
588 SlotIndex MBBStart = li_->getMBBStartIdx(CopyMBB);
589 SlotIndex LastUseIdx;
590 MachineOperand *LastUse =
591 lastRegisterUse(LR->start, CopyIdx.getPrevSlot(), li.reg, LastUseIdx);
593 MachineInstr *LastUseMI = LastUse->getParent();
594 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
601 // r1025<dead> = r1024<kill>
602 if (MBBStart < LR->end)
603 removeRange(li, MBBStart, LR->end, li_, tri_);
607 // There are uses before the copy, just shorten the live range to the end
609 LastUse->setIsKill();
610 removeRange(li, LastUseIdx.getDefIndex(), LR->end, li_, tri_);
611 LR->valno->addKill(LastUseIdx.getDefIndex());
612 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
613 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
615 // Last use is itself an identity code.
616 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
617 LastUseMI->getOperand(DeadIdx).setIsDead();
623 if (LR->start <= MBBStart && LR->end > MBBStart) {
624 if (LR->start == li_->getZeroIndex()) {
625 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
626 // Live-in to the function but dead. Remove it from entry live-in set.
627 mf_->begin()->removeLiveIn(li.reg);
629 // FIXME: Shorten intervals in BBs that reaches this BB.
635 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
636 /// computation, replace the copy by rematerialize the definition.
637 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
640 MachineInstr *CopyMI) {
641 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getUseIndex();
642 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
643 assert(SrcLR != SrcInt.end() && "Live range not found!");
644 VNInfo *ValNo = SrcLR->valno;
645 // If other defs can reach uses of this def, then it's not safe to perform
646 // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
648 if (ValNo->isPHIDef() || !ValNo->isDefAccurate() ||
649 ValNo->isUnused() || ValNo->hasPHIKill())
651 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
652 const TargetInstrDesc &TID = DefMI->getDesc();
653 if (!TID.isAsCheapAsAMove())
655 if (!tii_->isTriviallyReMaterializable(DefMI, AA))
657 bool SawStore = false;
658 if (!DefMI->isSafeToMove(tii_, SawStore, AA))
660 if (TID.getNumDefs() != 1)
662 if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF) {
663 // Make sure the copy destination register class fits the instruction
664 // definition register class. The mismatch can happen as a result of earlier
665 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
666 const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
667 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
668 if (mri_->getRegClass(DstReg) != RC)
670 } else if (!RC->contains(DstReg))
674 // If destination register has a sub-register index on it, make sure it mtches
675 // the instruction register class.
677 const TargetInstrDesc &TID = DefMI->getDesc();
678 if (TID.getNumDefs() != 1)
680 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
681 const TargetRegisterClass *DstSubRC =
682 DstRC->getSubRegisterRegClass(DstSubIdx);
683 const TargetRegisterClass *DefRC = TID.OpInfo[0].getRegClass(tri_);
686 else if (DefRC != DstSubRC)
690 SlotIndex DefIdx = CopyIdx.getDefIndex();
691 const LiveRange *DLR= li_->getInterval(DstReg).getLiveRangeContaining(DefIdx);
692 DLR->valno->setCopy(0);
693 // Don't forget to update sub-register intervals.
694 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
695 for (const unsigned* SR = tri_->getSubRegisters(DstReg); *SR; ++SR) {
696 if (!li_->hasInterval(*SR))
698 DLR = li_->getInterval(*SR).getLiveRangeContaining(DefIdx);
699 if (DLR && DLR->valno->getCopy() == CopyMI)
700 DLR->valno->setCopy(0);
704 // If copy kills the source register, find the last use and propagate
706 bool checkForDeadDef = false;
707 MachineBasicBlock *MBB = CopyMI->getParent();
708 if (CopyMI->killsRegister(SrcInt.reg))
709 if (!TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR)) {
710 checkForDeadDef = true;
713 MachineBasicBlock::iterator MII =
714 llvm::next(MachineBasicBlock::iterator(CopyMI));
715 tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI, tri_);
716 MachineInstr *NewMI = prior(MII);
718 if (checkForDeadDef) {
719 // PR4090 fix: Trim interval failed because there was no use of the
720 // source interval in this MBB. If the def is in this MBB too then we
721 // should mark it dead:
722 if (DefMI->getParent() == MBB) {
723 DefMI->addRegisterDead(SrcInt.reg, tri_);
724 SrcLR->end = SrcLR->start.getNextSlot();
728 // CopyMI may have implicit operands, transfer them over to the newly
729 // rematerialized instruction. And update implicit def interval valnos.
730 for (unsigned i = CopyMI->getDesc().getNumOperands(),
731 e = CopyMI->getNumOperands(); i != e; ++i) {
732 MachineOperand &MO = CopyMI->getOperand(i);
733 if (MO.isReg() && MO.isImplicit())
734 NewMI->addOperand(MO);
735 if (MO.isDef() && li_->hasInterval(MO.getReg())) {
736 unsigned Reg = MO.getReg();
737 DLR = li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
738 if (DLR && DLR->valno->getCopy() == CopyMI)
739 DLR->valno->setCopy(0);
743 TransferImplicitOps(CopyMI, NewMI);
744 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
745 CopyMI->eraseFromParent();
746 ReMatCopies.insert(CopyMI);
747 ReMatDefs.insert(DefMI);
752 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
753 /// update the subregister number if it is not zero. If DstReg is a
754 /// physical register and the existing subregister number of the def / use
755 /// being updated is not zero, make sure to set it to the correct physical
758 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
760 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
761 if (DstIsPhys && SubIdx) {
762 // Figure out the real physical register we are updating with.
763 DstReg = tri_->getSubReg(DstReg, SubIdx);
767 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
768 E = mri_->reg_end(); I != E; ) {
769 MachineOperand &O = I.getOperand();
770 MachineInstr *UseMI = &*I;
772 unsigned OldSubIdx = O.getSubReg();
774 unsigned UseDstReg = DstReg;
776 UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
778 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
779 if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
780 CopySrcSubIdx, CopyDstSubIdx) &&
781 CopySrcReg != CopyDstReg &&
782 CopySrcReg == SrcReg && CopyDstReg != UseDstReg) {
783 // If the use is a copy and it won't be coalesced away, and its source
784 // is defined by a trivial computation, try to rematerialize it instead.
785 if (ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg,
786 CopyDstSubIdx, UseMI))
795 // Sub-register indexes goes from small to large. e.g.
796 // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
797 // EAX: 1 -> AL, 2 -> AX
798 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
799 // sub-register 2 is also AX.
800 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
801 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
804 // Remove would-be duplicated kill marker.
805 if (O.isKill() && UseMI->killsRegister(DstReg))
809 // After updating the operand, check if the machine instruction has
810 // become a copy. If so, update its val# information.
811 if (JoinedCopies.count(UseMI))
814 const TargetInstrDesc &TID = UseMI->getDesc();
815 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
816 if (TID.getNumDefs() == 1 && TID.getNumOperands() > 2 &&
817 tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
818 CopySrcSubIdx, CopyDstSubIdx) &&
819 CopySrcReg != CopyDstReg &&
820 (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
821 allocatableRegs_[CopyDstReg])) {
822 LiveInterval &LI = li_->getInterval(CopyDstReg);
824 li_->getInstructionIndex(UseMI).getDefIndex();
825 if (const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx)) {
826 if (DLR->valno->def == DefIdx)
827 DLR->valno->setCopy(UseMI);
833 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
834 /// due to live range lengthening as the result of coalescing.
835 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
837 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
838 UE = mri_->use_end(); UI != UE; ++UI) {
839 MachineOperand &UseMO = UI.getOperand();
842 MachineInstr *UseMI = UseMO.getParent();
844 li_->getInstructionIndex(UseMI).getUseIndex();
845 const LiveRange *LR = LI.getLiveRangeContaining(UseIdx);
847 (!LR->valno->isKill(UseIdx.getDefIndex()) &&
848 LR->valno->def != UseIdx.getDefIndex())) {
849 // Interesting problem. After coalescing reg1027's def and kill are both
850 // at the same point: %reg1027,0.000000e+00 = [56,814:0) 0@70-(814)
853 // 60 %reg1027<def> = t2MOVr %reg1027, 14, %reg0, %reg0
854 // 68 %reg1027<def> = t2LDRi12 %reg1027<kill>, 8, 14, %reg0
855 // 76 t2CMPzri %reg1038<kill,undef>, 0, 14, %reg0, %CPSR<imp-def>
856 // 84 %reg1027<def> = t2MOVr %reg1027, 14, %reg0, %reg0
857 // 96 t2Bcc mbb<bb5,0x2030910>, 1, %CPSR<kill>
859 // Do not remove the kill marker on t2LDRi12.
860 UseMO.setIsKill(false);
865 /// removeIntervalIfEmpty - Check if the live interval of a physical register
866 /// is empty, if so remove it and also remove the empty intervals of its
867 /// sub-registers. Return true if live interval is removed.
868 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
869 const TargetRegisterInfo *tri_) {
871 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
872 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
873 if (!li_->hasInterval(*SR))
875 LiveInterval &sli = li_->getInterval(*SR);
877 li_->removeInterval(*SR);
879 li_->removeInterval(li.reg);
885 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
886 /// Return true if live interval is removed.
887 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
888 MachineInstr *CopyMI) {
889 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
890 LiveInterval::iterator MLR =
891 li.FindLiveRangeContaining(CopyIdx.getDefIndex());
893 return false; // Already removed by ShortenDeadCopySrcLiveRange.
894 SlotIndex RemoveStart = MLR->start;
895 SlotIndex RemoveEnd = MLR->end;
896 SlotIndex DefIdx = CopyIdx.getDefIndex();
897 // Remove the liverange that's defined by this.
898 if (RemoveStart == DefIdx && RemoveEnd == DefIdx.getStoreIndex()) {
899 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
900 return removeIntervalIfEmpty(li, li_, tri_);
905 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
906 /// the val# it defines. If the live interval becomes empty, remove it as well.
907 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
908 MachineInstr *DefMI) {
909 SlotIndex DefIdx = li_->getInstructionIndex(DefMI).getDefIndex();
910 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
911 if (DefIdx != MLR->valno->def)
913 li.removeValNo(MLR->valno);
914 return removeIntervalIfEmpty(li, li_, tri_);
917 /// PropagateDeadness - Propagate the dead marker to the instruction which
918 /// defines the val#.
919 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
920 SlotIndex &LRStart, LiveIntervals *li_,
921 const TargetRegisterInfo* tri_) {
922 MachineInstr *DefMI =
923 li_->getInstructionFromIndex(LRStart.getDefIndex());
924 if (DefMI && DefMI != CopyMI) {
925 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false);
927 DefMI->getOperand(DeadIdx).setIsDead();
929 DefMI->addOperand(MachineOperand::CreateReg(li.reg,
930 /*def*/true, /*implicit*/true, /*kill*/false, /*dead*/true));
931 LRStart = LRStart.getNextSlot();
935 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
936 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
937 /// ends the live range there. If there isn't another use, then this live range
938 /// is dead. Return true if live interval is removed.
940 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
941 MachineInstr *CopyMI) {
942 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
943 if (CopyIdx == SlotIndex()) {
944 // FIXME: special case: function live in. It can be a general case if the
945 // first instruction index starts at > 0 value.
946 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
947 // Live-in to the function but dead. Remove it from entry live-in set.
948 if (mf_->begin()->isLiveIn(li.reg))
949 mf_->begin()->removeLiveIn(li.reg);
950 const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
951 removeRange(li, LR->start, LR->end, li_, tri_);
952 return removeIntervalIfEmpty(li, li_, tri_);
955 LiveInterval::iterator LR =
956 li.FindLiveRangeContaining(CopyIdx.getPrevIndex().getStoreIndex());
958 // Livein but defined by a phi.
961 SlotIndex RemoveStart = LR->start;
962 SlotIndex RemoveEnd = CopyIdx.getStoreIndex();
963 if (LR->end > RemoveEnd)
964 // More uses past this copy? Nothing to do.
967 // If there is a last use in the same bb, we can't remove the live range.
968 // Shorten the live interval and return.
969 MachineBasicBlock *CopyMBB = CopyMI->getParent();
970 if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
973 // There are other kills of the val#. Nothing to do.
974 if (!li.isOnlyLROfValNo(LR))
977 MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
978 if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
979 // If the live range starts in another mbb and the copy mbb is not a fall
980 // through mbb, then we can only cut the range from the beginning of the
982 RemoveStart = li_->getMBBStartIdx(CopyMBB).getNextIndex().getBaseIndex();
984 if (LR->valno->def == RemoveStart) {
985 // If the def MI defines the val# and this copy is the only kill of the
986 // val#, then propagate the dead marker.
987 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
990 if (LR->valno->isKill(RemoveEnd))
991 LR->valno->removeKill(RemoveEnd);
994 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
995 return removeIntervalIfEmpty(li, li_, tri_);
998 /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
999 /// from an implicit def to another register can be coalesced away.
1000 bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
1002 LiveInterval &ImpLi) const{
1003 if (!CopyMI->killsRegister(ImpLi.reg))
1005 // Make sure this is the only use.
1006 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(ImpLi.reg),
1007 UE = mri_->use_end(); UI != UE;) {
1008 MachineInstr *UseMI = &*UI;
1010 if (CopyMI == UseMI || JoinedCopies.count(UseMI))
1018 /// isWinToJoinVRWithSrcPhysReg - Return true if it's worth while to join a
1019 /// a virtual destination register with physical source register.
1021 SimpleRegisterCoalescing::isWinToJoinVRWithSrcPhysReg(MachineInstr *CopyMI,
1022 MachineBasicBlock *CopyMBB,
1023 LiveInterval &DstInt,
1024 LiveInterval &SrcInt) {
1025 // If the virtual register live interval is long but it has low use desity,
1026 // do not join them, instead mark the physical register as its allocation
1028 const TargetRegisterClass *RC = mri_->getRegClass(DstInt.reg);
1029 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1030 unsigned Length = li_->getApproximateInstructionCount(DstInt);
1031 if (Length > Threshold &&
1032 (((float)std::distance(mri_->use_begin(DstInt.reg),
1033 mri_->use_end()) / Length) < (1.0 / Threshold)))
1036 // If the virtual register live interval extends into a loop, turn down
1039 li_->getInstructionIndex(CopyMI).getDefIndex();
1040 const MachineLoop *L = loopInfo->getLoopFor(CopyMBB);
1042 // Let's see if the virtual register live interval extends into the loop.
1043 LiveInterval::iterator DLR = DstInt.FindLiveRangeContaining(CopyIdx);
1044 assert(DLR != DstInt.end() && "Live range not found!");
1045 DLR = DstInt.FindLiveRangeContaining(DLR->end.getNextSlot());
1046 if (DLR != DstInt.end()) {
1047 CopyMBB = li_->getMBBFromIndex(DLR->start);
1048 L = loopInfo->getLoopFor(CopyMBB);
1052 if (!L || Length <= Threshold)
1055 SlotIndex UseIdx = CopyIdx.getUseIndex();
1056 LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1057 MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1058 if (loopInfo->getLoopFor(SMBB) != L) {
1059 if (!loopInfo->isLoopHeader(CopyMBB))
1061 // If vr's live interval extends pass the loop header, do not join.
1062 for (MachineBasicBlock::succ_iterator SI = CopyMBB->succ_begin(),
1063 SE = CopyMBB->succ_end(); SI != SE; ++SI) {
1064 MachineBasicBlock *SuccMBB = *SI;
1065 if (SuccMBB == CopyMBB)
1067 if (DstInt.overlaps(li_->getMBBStartIdx(SuccMBB),
1068 li_->getMBBEndIdx(SuccMBB).getNextIndex().getBaseIndex()))
1075 /// isWinToJoinVRWithDstPhysReg - Return true if it's worth while to join a
1076 /// copy from a virtual source register to a physical destination register.
1078 SimpleRegisterCoalescing::isWinToJoinVRWithDstPhysReg(MachineInstr *CopyMI,
1079 MachineBasicBlock *CopyMBB,
1080 LiveInterval &DstInt,
1081 LiveInterval &SrcInt) {
1082 // If the virtual register live interval is long but it has low use desity,
1083 // do not join them, instead mark the physical register as its allocation
1085 const TargetRegisterClass *RC = mri_->getRegClass(SrcInt.reg);
1086 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1087 unsigned Length = li_->getApproximateInstructionCount(SrcInt);
1088 if (Length > Threshold &&
1089 (((float)std::distance(mri_->use_begin(SrcInt.reg),
1090 mri_->use_end()) / Length) < (1.0 / Threshold)))
1094 // Must be implicit_def.
1097 // If the virtual register live interval is defined or cross a loop, turn
1098 // down aggressiveness.
1100 li_->getInstructionIndex(CopyMI).getDefIndex();
1101 SlotIndex UseIdx = CopyIdx.getUseIndex();
1102 LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1103 assert(SLR != SrcInt.end() && "Live range not found!");
1104 SLR = SrcInt.FindLiveRangeContaining(SLR->start.getPrevSlot());
1105 if (SLR == SrcInt.end())
1107 MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1108 const MachineLoop *L = loopInfo->getLoopFor(SMBB);
1110 if (!L || Length <= Threshold)
1113 if (loopInfo->getLoopFor(CopyMBB) != L) {
1114 if (SMBB != L->getLoopLatch())
1116 // If vr's live interval is extended from before the loop latch, do not
1118 for (MachineBasicBlock::pred_iterator PI = SMBB->pred_begin(),
1119 PE = SMBB->pred_end(); PI != PE; ++PI) {
1120 MachineBasicBlock *PredMBB = *PI;
1121 if (PredMBB == SMBB)
1123 if (SrcInt.overlaps(li_->getMBBStartIdx(PredMBB),
1124 li_->getMBBEndIdx(PredMBB).getNextIndex().getBaseIndex()))
1131 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
1132 /// two virtual registers from different register classes.
1134 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned LargeReg,
1136 unsigned Threshold) {
1137 // Then make sure the intervals are *short*.
1138 LiveInterval &LargeInt = li_->getInterval(LargeReg);
1139 LiveInterval &SmallInt = li_->getInterval(SmallReg);
1140 unsigned LargeSize = li_->getApproximateInstructionCount(LargeInt);
1141 unsigned SmallSize = li_->getApproximateInstructionCount(SmallInt);
1142 if (SmallSize > Threshold || LargeSize > Threshold)
1143 if ((float)std::distance(mri_->use_begin(SmallReg),
1144 mri_->use_end()) / SmallSize <
1145 (float)std::distance(mri_->use_begin(LargeReg),
1146 mri_->use_end()) / LargeSize)
1151 /// HasIncompatibleSubRegDefUse - If we are trying to coalesce a virtual
1152 /// register with a physical register, check if any of the virtual register
1153 /// operand is a sub-register use or def. If so, make sure it won't result
1154 /// in an illegal extract_subreg or insert_subreg instruction. e.g.
1155 /// vr1024 = extract_subreg vr1025, 1
1157 /// vr1024 = mov8rr AH
1158 /// If vr1024 is coalesced with AH, the extract_subreg is now illegal since
1159 /// AH does not have a super-reg whose sub-register 1 is AH.
1161 SimpleRegisterCoalescing::HasIncompatibleSubRegDefUse(MachineInstr *CopyMI,
1164 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(VirtReg),
1165 E = mri_->reg_end(); I != E; ++I) {
1166 MachineOperand &O = I.getOperand();
1167 MachineInstr *MI = &*I;
1168 if (MI == CopyMI || JoinedCopies.count(MI))
1170 unsigned SubIdx = O.getSubReg();
1171 if (SubIdx && !tri_->getSubReg(PhysReg, SubIdx))
1173 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1174 SubIdx = MI->getOperand(2).getImm();
1175 if (O.isUse() && !tri_->getSubReg(PhysReg, SubIdx))
1178 unsigned SrcReg = MI->getOperand(1).getReg();
1179 const TargetRegisterClass *RC =
1180 TargetRegisterInfo::isPhysicalRegister(SrcReg)
1181 ? tri_->getPhysicalRegisterRegClass(SrcReg)
1182 : mri_->getRegClass(SrcReg);
1183 if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
1187 if (MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
1188 MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
1189 SubIdx = MI->getOperand(3).getImm();
1190 if (VirtReg == MI->getOperand(0).getReg()) {
1191 if (!tri_->getSubReg(PhysReg, SubIdx))
1194 unsigned DstReg = MI->getOperand(0).getReg();
1195 const TargetRegisterClass *RC =
1196 TargetRegisterInfo::isPhysicalRegister(DstReg)
1197 ? tri_->getPhysicalRegisterRegClass(DstReg)
1198 : mri_->getRegClass(DstReg);
1199 if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
1208 /// CanJoinExtractSubRegToPhysReg - Return true if it's possible to coalesce
1209 /// an extract_subreg where dst is a physical register, e.g.
1210 /// cl = EXTRACT_SUBREG reg1024, 1
1212 SimpleRegisterCoalescing::CanJoinExtractSubRegToPhysReg(unsigned DstReg,
1213 unsigned SrcReg, unsigned SubIdx,
1214 unsigned &RealDstReg) {
1215 const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
1216 RealDstReg = tri_->getMatchingSuperReg(DstReg, SubIdx, RC);
1217 assert(RealDstReg && "Invalid extract_subreg instruction!");
1219 // For this type of EXTRACT_SUBREG, conservatively
1220 // check if the live interval of the source register interfere with the
1221 // actual super physical register we are trying to coalesce with.
1222 LiveInterval &RHS = li_->getInterval(SrcReg);
1223 if (li_->hasInterval(RealDstReg) &&
1224 RHS.overlaps(li_->getInterval(RealDstReg))) {
1226 errs() << "Interfere with register ";
1227 li_->getInterval(RealDstReg).print(errs(), tri_);
1229 return false; // Not coalescable
1231 for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
1232 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1234 errs() << "Interfere with sub-register ";
1235 li_->getInterval(*SR).print(errs(), tri_);
1237 return false; // Not coalescable
1242 /// CanJoinInsertSubRegToPhysReg - Return true if it's possible to coalesce
1243 /// an insert_subreg where src is a physical register, e.g.
1244 /// reg1024 = INSERT_SUBREG reg1024, c1, 0
1246 SimpleRegisterCoalescing::CanJoinInsertSubRegToPhysReg(unsigned DstReg,
1247 unsigned SrcReg, unsigned SubIdx,
1248 unsigned &RealSrcReg) {
1249 const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
1250 RealSrcReg = tri_->getMatchingSuperReg(SrcReg, SubIdx, RC);
1251 assert(RealSrcReg && "Invalid extract_subreg instruction!");
1253 LiveInterval &RHS = li_->getInterval(DstReg);
1254 if (li_->hasInterval(RealSrcReg) &&
1255 RHS.overlaps(li_->getInterval(RealSrcReg))) {
1257 errs() << "Interfere with register ";
1258 li_->getInterval(RealSrcReg).print(errs(), tri_);
1260 return false; // Not coalescable
1262 for (const unsigned* SR = tri_->getSubRegisters(RealSrcReg); *SR; ++SR)
1263 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1265 errs() << "Interfere with sub-register ";
1266 li_->getInterval(*SR).print(errs(), tri_);
1268 return false; // Not coalescable
1273 /// getRegAllocPreference - Return register allocation preference register.
1275 static unsigned getRegAllocPreference(unsigned Reg, MachineFunction &MF,
1276 MachineRegisterInfo *MRI,
1277 const TargetRegisterInfo *TRI) {
1278 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1280 std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
1281 return TRI->ResolveRegAllocHint(Hint.first, Hint.second, MF);
1284 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1285 /// which are the src/dst of the copy instruction CopyMI. This returns true
1286 /// if the copy was successfully coalesced away. If it is not currently
1287 /// possible to coalesce this interval, but it may be possible if other
1288 /// things get coalesced, then it returns true by reference in 'Again'.
1289 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1290 MachineInstr *CopyMI = TheCopy.MI;
1293 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1294 return false; // Already done.
1296 DEBUG(errs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1298 unsigned SrcReg, DstReg, SrcSubIdx = 0, DstSubIdx = 0;
1299 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
1300 bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG;
1301 bool isSubRegToReg = CopyMI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG;
1302 unsigned SubIdx = 0;
1304 DstReg = CopyMI->getOperand(0).getReg();
1305 DstSubIdx = CopyMI->getOperand(0).getSubReg();
1306 SrcReg = CopyMI->getOperand(1).getReg();
1307 SrcSubIdx = CopyMI->getOperand(2).getImm();
1308 } else if (isInsSubReg || isSubRegToReg) {
1309 DstReg = CopyMI->getOperand(0).getReg();
1310 DstSubIdx = CopyMI->getOperand(3).getImm();
1311 SrcReg = CopyMI->getOperand(2).getReg();
1312 SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1313 if (SrcSubIdx && SrcSubIdx != DstSubIdx) {
1314 // r1025 = INSERT_SUBREG r1025, r1024<2>, 2 Then r1024 has already been
1315 // coalesced to a larger register so the subreg indices cancel out.
1316 DEBUG(errs() << "\tSource of insert_subreg or subreg_to_reg is already "
1317 "coalesced to another register.\n");
1318 return false; // Not coalescable.
1320 } else if (tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
1321 if (SrcSubIdx && DstSubIdx && SrcSubIdx != DstSubIdx) {
1322 // e.g. %reg16404:1<def> = MOV8rr %reg16412:2<kill>
1324 return false; // Not coalescable.
1327 llvm_unreachable("Unrecognized copy instruction!");
1330 // If they are already joined we continue.
1331 if (SrcReg == DstReg) {
1332 DEBUG(errs() << "\tCopy already coalesced.\n");
1333 return false; // Not coalescable.
1336 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1337 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1339 // If they are both physical registers, we cannot join them.
1340 if (SrcIsPhys && DstIsPhys) {
1341 DEBUG(errs() << "\tCan not coalesce physregs.\n");
1342 return false; // Not coalescable.
1345 // We only join virtual registers with allocatable physical registers.
1346 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
1347 DEBUG(errs() << "\tSrc reg is unallocatable physreg.\n");
1348 return false; // Not coalescable.
1350 if (DstIsPhys && !allocatableRegs_[DstReg]) {
1351 DEBUG(errs() << "\tDst reg is unallocatable physreg.\n");
1352 return false; // Not coalescable.
1355 // Check that a physical source register is compatible with dst regclass
1357 unsigned SrcSubReg = SrcSubIdx ?
1358 tri_->getSubReg(SrcReg, SrcSubIdx) : SrcReg;
1359 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
1360 const TargetRegisterClass *DstSubRC = DstRC;
1362 DstSubRC = DstRC->getSubRegisterRegClass(DstSubIdx);
1363 assert(DstSubRC && "Illegal subregister index");
1364 if (!DstSubRC->contains(SrcSubReg)) {
1365 DEBUG(errs() << "\tIncompatible destination regclass: "
1366 << tri_->getName(SrcSubReg) << " not in "
1367 << DstSubRC->getName() << ".\n");
1368 return false; // Not coalescable.
1372 // Check that a physical dst register is compatible with source regclass
1374 unsigned DstSubReg = DstSubIdx ?
1375 tri_->getSubReg(DstReg, DstSubIdx) : DstReg;
1376 const TargetRegisterClass *SrcRC = mri_->getRegClass(SrcReg);
1377 const TargetRegisterClass *SrcSubRC = SrcRC;
1379 SrcSubRC = SrcRC->getSubRegisterRegClass(SrcSubIdx);
1380 assert(SrcSubRC && "Illegal subregister index");
1381 if (!SrcSubRC->contains(DstSubReg)) {
1382 DEBUG(errs() << "\tIncompatible source regclass: "
1383 << tri_->getName(DstSubReg) << " not in "
1384 << SrcSubRC->getName() << ".\n");
1386 return false; // Not coalescable.
1390 // Should be non-null only when coalescing to a sub-register class.
1391 bool CrossRC = false;
1392 const TargetRegisterClass *SrcRC= SrcIsPhys ? 0 : mri_->getRegClass(SrcReg);
1393 const TargetRegisterClass *DstRC= DstIsPhys ? 0 : mri_->getRegClass(DstReg);
1394 const TargetRegisterClass *NewRC = NULL;
1395 MachineBasicBlock *CopyMBB = CopyMI->getParent();
1396 unsigned RealDstReg = 0;
1397 unsigned RealSrcReg = 0;
1398 if (isExtSubReg || isInsSubReg || isSubRegToReg) {
1399 SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
1400 if (SrcIsPhys && isExtSubReg) {
1401 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
1402 // coalesced with AX.
1403 unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
1405 // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
1406 // coalesced to a larger register so the subreg indices cancel out.
1407 if (DstSubIdx != SubIdx) {
1408 DEBUG(errs() << "\t Sub-register indices mismatch.\n");
1409 return false; // Not coalescable.
1412 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
1414 } else if (DstIsPhys && (isInsSubReg || isSubRegToReg)) {
1415 // EAX = INSERT_SUBREG EAX, r1024, 0
1416 unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1418 // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
1419 // coalesced to a larger register so the subreg indices cancel out.
1420 if (SrcSubIdx != SubIdx) {
1421 DEBUG(errs() << "\t Sub-register indices mismatch.\n");
1422 return false; // Not coalescable.
1425 DstReg = tri_->getSubReg(DstReg, SubIdx);
1427 } else if ((DstIsPhys && isExtSubReg) ||
1428 (SrcIsPhys && (isInsSubReg || isSubRegToReg))) {
1429 if (!isSubRegToReg && CopyMI->getOperand(1).getSubReg()) {
1430 DEBUG(errs() << "\tSrc of extract_subreg already coalesced with reg"
1431 << " of a super-class.\n");
1432 return false; // Not coalescable.
1436 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealDstReg))
1437 return false; // Not coalescable
1439 if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1440 return false; // Not coalescable
1444 unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
1445 : CopyMI->getOperand(2).getSubReg();
1447 if (OldSubIdx == SubIdx && !differingRegisterClasses(SrcReg, DstReg))
1448 // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
1449 // coalesced to a larger register so the subreg indices cancel out.
1450 // Also check if the other larger register is of the same register
1451 // class as the would be resulting register.
1454 DEBUG(errs() << "\t Sub-register indices mismatch.\n");
1455 return false; // Not coalescable.
1459 if (!DstIsPhys && !SrcIsPhys) {
1460 if (isInsSubReg || isSubRegToReg) {
1461 NewRC = tri_->getMatchingSuperRegClass(DstRC, SrcRC, SubIdx);
1462 } else // extract_subreg {
1463 NewRC = tri_->getMatchingSuperRegClass(SrcRC, DstRC, SubIdx);
1466 DEBUG(errs() << "\t Conflicting sub-register indices.\n");
1467 return false; // Not coalescable
1470 unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
1471 unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
1472 unsigned Limit= allocatableRCRegs_[mri_->getRegClass(SmallReg)].count();
1473 if (!isWinToJoinCrossClass(LargeReg, SmallReg, Limit)) {
1474 Again = true; // May be possible to coalesce later.
1479 } else if (differingRegisterClasses(SrcReg, DstReg)) {
1480 if (DisableCrossClassJoin)
1484 // FIXME: What if the result of a EXTRACT_SUBREG is then coalesced
1485 // with another? If it's the resulting destination register, then
1486 // the subidx must be propagated to uses (but only those defined
1487 // by the EXTRACT_SUBREG). If it's being coalesced into another
1488 // register, it should be safe because register is assumed to have
1489 // the register class of the super-register.
1491 // Process moves where one of the registers have a sub-register index.
1492 MachineOperand *DstMO = CopyMI->findRegisterDefOperand(DstReg);
1493 MachineOperand *SrcMO = CopyMI->findRegisterUseOperand(SrcReg);
1494 SubIdx = DstMO->getSubReg();
1496 if (SrcMO->getSubReg())
1497 // FIXME: can we handle this?
1499 // This is not an insert_subreg but it looks like one.
1500 // e.g. %reg1024:4 = MOV32rr %EAX
1503 if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1504 return false; // Not coalescable
1508 SubIdx = SrcMO->getSubReg();
1510 // This is not a extract_subreg but it looks like one.
1511 // e.g. %cl = MOV16rr %reg1024:1
1514 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx,RealDstReg))
1515 return false; // Not coalescable
1521 unsigned LargeReg = SrcReg;
1522 unsigned SmallReg = DstReg;
1524 // Now determine the register class of the joined register.
1526 if (SubIdx && DstRC && DstRC->isASubClass()) {
1527 // This is a move to a sub-register class. However, the source is a
1528 // sub-register of a larger register class. We don't know what should
1529 // the register class be. FIXME.
1533 if (!DstIsPhys && !SrcIsPhys)
1535 } else if (!SrcIsPhys && !DstIsPhys) {
1536 NewRC = getCommonSubClass(SrcRC, DstRC);
1538 DEBUG(errs() << "\tDisjoint regclasses: "
1539 << SrcRC->getName() << ", "
1540 << DstRC->getName() << ".\n");
1541 return false; // Not coalescable.
1543 if (DstRC->getSize() > SrcRC->getSize())
1544 std::swap(LargeReg, SmallReg);
1547 // If we are joining two virtual registers and the resulting register
1548 // class is more restrictive (fewer register, smaller size). Check if it's
1549 // worth doing the merge.
1550 if (!SrcIsPhys && !DstIsPhys &&
1551 (isExtSubReg || DstRC->isASubClass()) &&
1552 !isWinToJoinCrossClass(LargeReg, SmallReg,
1553 allocatableRCRegs_[NewRC].count())) {
1554 DEBUG(errs() << "\tSrc/Dest are different register classes.\n");
1555 // Allow the coalescer to try again in case either side gets coalesced to
1556 // a physical register that's compatible with the other side. e.g.
1557 // r1024 = MOV32to32_ r1025
1558 // But later r1024 is assigned EAX then r1025 may be coalesced with EAX.
1559 Again = true; // May be possible to coalesce later.
1564 // Will it create illegal extract_subreg / insert_subreg?
1565 if (SrcIsPhys && HasIncompatibleSubRegDefUse(CopyMI, DstReg, SrcReg))
1567 if (DstIsPhys && HasIncompatibleSubRegDefUse(CopyMI, SrcReg, DstReg))
1570 LiveInterval &SrcInt = li_->getInterval(SrcReg);
1571 LiveInterval &DstInt = li_->getInterval(DstReg);
1572 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
1573 "Register mapping is horribly broken!");
1576 errs() << "\t\tInspecting "; SrcInt.print(errs(), tri_);
1577 errs() << " and "; DstInt.print(errs(), tri_);
1581 // Save a copy of the virtual register live interval. We'll manually
1582 // merge this into the "real" physical register live interval this is
1584 LiveInterval *SavedLI = 0;
1586 SavedLI = li_->dupInterval(&SrcInt);
1587 else if (RealSrcReg)
1588 SavedLI = li_->dupInterval(&DstInt);
1590 // Check if it is necessary to propagate "isDead" property.
1591 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg) {
1592 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1593 bool isDead = mopd->isDead();
1595 // We need to be careful about coalescing a source physical register with a
1596 // virtual register. Once the coalescing is done, it cannot be broken and
1597 // these are not spillable! If the destination interval uses are far away,
1598 // think twice about coalescing them!
1599 if (!isDead && (SrcIsPhys || DstIsPhys)) {
1600 // If the copy is in a loop, take care not to coalesce aggressively if the
1601 // src is coming in from outside the loop (or the dst is out of the loop).
1602 // If it's not in a loop, then determine whether to join them base purely
1603 // by the length of the interval.
1604 if (PhysJoinTweak) {
1606 if (!isWinToJoinVRWithSrcPhysReg(CopyMI, CopyMBB, DstInt, SrcInt)) {
1607 mri_->setRegAllocationHint(DstInt.reg, 0, SrcReg);
1609 DEBUG(errs() << "\tMay tie down a physical register, abort!\n");
1610 Again = true; // May be possible to coalesce later.
1614 if (!isWinToJoinVRWithDstPhysReg(CopyMI, CopyMBB, DstInt, SrcInt)) {
1615 mri_->setRegAllocationHint(SrcInt.reg, 0, DstReg);
1617 DEBUG(errs() << "\tMay tie down a physical register, abort!\n");
1618 Again = true; // May be possible to coalesce later.
1623 // If the virtual register live interval is long but it has low use
1624 // density, do not join them, instead mark the physical register as its
1625 // allocation preference.
1626 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1627 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1628 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1629 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1630 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1631 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1632 float Ratio = 1.0 / Threshold;
1633 if (Length > Threshold &&
1634 (((float)std::distance(mri_->use_begin(JoinVReg),
1635 mri_->use_end()) / Length) < Ratio)) {
1636 mri_->setRegAllocationHint(JoinVInt.reg, 0, JoinPReg);
1638 DEBUG(errs() << "\tMay tie down a physical register, abort!\n");
1639 Again = true; // May be possible to coalesce later.
1646 // Okay, attempt to join these two intervals. On failure, this returns false.
1647 // Otherwise, if one of the intervals being joined is a physreg, this method
1648 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1649 // been modified, so we can use this information below to update aliases.
1650 bool Swapped = false;
1651 // If SrcInt is implicitly defined, it's safe to coalesce.
1652 bool isEmpty = SrcInt.empty();
1653 if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
1654 // Only coalesce an empty interval (defined by implicit_def) with
1655 // another interval which has a valno defined by the CopyMI and the CopyMI
1656 // is a kill of the implicit def.
1657 DEBUG(errs() << "Not profitable!\n");
1661 if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
1662 // Coalescing failed.
1664 // If definition of source is defined by trivial computation, try
1665 // rematerializing it.
1666 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
1667 ReMaterializeTrivialDef(SrcInt, DstReg, DstSubIdx, CopyMI))
1670 // If we can eliminate the copy without merging the live ranges, do so now.
1671 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
1672 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1673 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
1674 JoinedCopies.insert(CopyMI);
1678 // Otherwise, we are unable to join the intervals.
1679 DEBUG(errs() << "Interference!\n");
1680 Again = true; // May be possible to coalesce later.
1684 LiveInterval *ResSrcInt = &SrcInt;
1685 LiveInterval *ResDstInt = &DstInt;
1687 std::swap(SrcReg, DstReg);
1688 std::swap(ResSrcInt, ResDstInt);
1690 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1691 "LiveInterval::join didn't work right!");
1693 // If we're about to merge live ranges into a physical register live interval,
1694 // we have to update any aliased register's live ranges to indicate that they
1695 // have clobbered values for this range.
1696 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1697 // If this is a extract_subreg where dst is a physical register, e.g.
1698 // cl = EXTRACT_SUBREG reg1024, 1
1699 // then create and update the actual physical register allocated to RHS.
1700 if (RealDstReg || RealSrcReg) {
1701 LiveInterval &RealInt =
1702 li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
1703 for (LiveInterval::const_vni_iterator I = SavedLI->vni_begin(),
1704 E = SavedLI->vni_end(); I != E; ++I) {
1705 const VNInfo *ValNo = *I;
1706 VNInfo *NewValNo = RealInt.getNextValue(ValNo->def, ValNo->getCopy(),
1707 false, // updated at *
1708 li_->getVNInfoAllocator());
1709 NewValNo->setFlags(ValNo->getFlags()); // * updated here.
1710 RealInt.addKills(NewValNo, ValNo->kills);
1711 RealInt.MergeValueInAsValue(*SavedLI, ValNo, NewValNo);
1713 RealInt.weight += SavedLI->weight;
1714 DstReg = RealDstReg ? RealDstReg : RealSrcReg;
1717 // Update the liveintervals of sub-registers.
1718 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
1719 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*li_, *ResSrcInt,
1720 li_->getVNInfoAllocator());
1723 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1724 // larger super-register.
1725 if ((isExtSubReg || isInsSubReg || isSubRegToReg) &&
1726 !SrcIsPhys && !DstIsPhys) {
1727 if ((isExtSubReg && !Swapped) ||
1728 ((isInsSubReg || isSubRegToReg) && Swapped)) {
1729 ResSrcInt->Copy(*ResDstInt, mri_, li_->getVNInfoAllocator());
1730 std::swap(SrcReg, DstReg);
1731 std::swap(ResSrcInt, ResDstInt);
1735 // Coalescing to a virtual register that is of a sub-register class of the
1736 // other. Make sure the resulting register is set to the right register class.
1740 // This may happen even if it's cross-rc coalescing. e.g.
1741 // %reg1026<def> = SUBREG_TO_REG 0, %reg1037<kill>, 4
1742 // reg1026 -> GR64, reg1037 -> GR32_ABCD. The resulting register will have to
1743 // be allocate a register from GR64_ABCD.
1745 mri_->setRegClass(DstReg, NewRC);
1747 // Remember to delete the copy instruction.
1748 JoinedCopies.insert(CopyMI);
1750 // Some live range has been lengthened due to colaescing, eliminate the
1751 // unnecessary kills.
1752 RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1753 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1754 RemoveUnnecessaryKills(DstReg, *ResDstInt);
1756 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1758 // SrcReg is guarateed to be the register whose live interval that is
1760 li_->removeInterval(SrcReg);
1762 // Update regalloc hint.
1763 tri_->UpdateRegAllocHint(SrcReg, DstReg, *mf_);
1765 // Manually deleted the live interval copy.
1771 // If resulting interval has a preference that no longer fits because of subreg
1772 // coalescing, just clear the preference.
1773 unsigned Preference = getRegAllocPreference(ResDstInt->reg, *mf_, mri_, tri_);
1774 if (Preference && (isExtSubReg || isInsSubReg || isSubRegToReg) &&
1775 TargetRegisterInfo::isVirtualRegister(ResDstInt->reg)) {
1776 const TargetRegisterClass *RC = mri_->getRegClass(ResDstInt->reg);
1777 if (!RC->contains(Preference))
1778 mri_->setRegAllocationHint(ResDstInt->reg, 0, 0);
1782 errs() << "\n\t\tJoined. Result = ";
1783 ResDstInt->print(errs(), tri_);
1791 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1792 /// compute what the resultant value numbers for each value in the input two
1793 /// ranges will be. This is complicated by copies between the two which can
1794 /// and will commonly cause multiple value numbers to be merged into one.
1796 /// VN is the value number that we're trying to resolve. InstDefiningValue
1797 /// keeps track of the new InstDefiningValue assignment for the result
1798 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1799 /// whether a value in this or other is a copy from the opposite set.
1800 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1801 /// already been assigned.
1803 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1804 /// contains the value number the copy is from.
1806 static unsigned ComputeUltimateVN(VNInfo *VNI,
1807 SmallVector<VNInfo*, 16> &NewVNInfo,
1808 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1809 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1810 SmallVector<int, 16> &ThisValNoAssignments,
1811 SmallVector<int, 16> &OtherValNoAssignments) {
1812 unsigned VN = VNI->id;
1814 // If the VN has already been computed, just return it.
1815 if (ThisValNoAssignments[VN] >= 0)
1816 return ThisValNoAssignments[VN];
1817 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
1819 // If this val is not a copy from the other val, then it must be a new value
1820 // number in the destination.
1821 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1822 if (I == ThisFromOther.end()) {
1823 NewVNInfo.push_back(VNI);
1824 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1826 VNInfo *OtherValNo = I->second;
1828 // Otherwise, this *is* a copy from the RHS. If the other side has already
1829 // been computed, return it.
1830 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1831 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1833 // Mark this value number as currently being computed, then ask what the
1834 // ultimate value # of the other value is.
1835 ThisValNoAssignments[VN] = -2;
1836 unsigned UltimateVN =
1837 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1838 OtherValNoAssignments, ThisValNoAssignments);
1839 return ThisValNoAssignments[VN] = UltimateVN;
1842 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
1843 return std::find(V.begin(), V.end(), Val) != V.end();
1846 static bool isValNoDefMove(const MachineInstr *MI, unsigned DR, unsigned SR,
1847 const TargetInstrInfo *TII,
1848 const TargetRegisterInfo *TRI) {
1849 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1850 if (TII->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
1852 else if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1853 DstReg = MI->getOperand(0).getReg();
1854 SrcReg = MI->getOperand(1).getReg();
1855 } else if (MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG ||
1856 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
1857 DstReg = MI->getOperand(0).getReg();
1858 SrcReg = MI->getOperand(2).getReg();
1861 return (SrcReg == SR || TRI->isSuperRegister(SR, SrcReg)) &&
1862 (DstReg == DR || TRI->isSuperRegister(DR, DstReg));
1865 /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1866 /// the specified live interval is defined by a copy from the specified
1868 bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1871 unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1874 // FIXME: Do isPHIDef and isDefAccurate both need to be tested?
1875 if ((LR->valno->isPHIDef() || !LR->valno->isDefAccurate()) &&
1876 TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1877 *tri_->getSuperRegisters(li.reg)) {
1878 // It's a sub-register live interval, we may not have precise information.
1880 MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1881 if (DefMI && isValNoDefMove(DefMI, li.reg, Reg, tii_, tri_)) {
1882 // Cache computed info.
1883 LR->valno->def = LR->start;
1884 LR->valno->setCopy(DefMI);
1892 /// ValueLiveAt - Return true if the LiveRange pointed to by the given
1893 /// iterator, or any subsequent range with the same value number,
1894 /// is live at the given point.
1895 bool SimpleRegisterCoalescing::ValueLiveAt(LiveInterval::iterator LRItr,
1896 LiveInterval::iterator LREnd,
1897 SlotIndex defPoint) const {
1898 for (const VNInfo *valno = LRItr->valno;
1899 (LRItr != LREnd) && (LRItr->valno == valno); ++LRItr) {
1900 if (LRItr->contains(defPoint))
1908 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1909 /// caller of this method must guarantee that the RHS only contains a single
1910 /// value number and that the RHS is not defined by a copy from this
1911 /// interval. This returns false if the intervals are not joinable, or it
1912 /// joins them and returns true.
1913 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
1914 assert(RHS.containsOneValue());
1916 // Some number (potentially more than one) value numbers in the current
1917 // interval may be defined as copies from the RHS. Scan the overlapping
1918 // portions of the LHS and RHS, keeping track of this and looking for
1919 // overlapping live ranges that are NOT defined as copies. If these exist, we
1922 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1923 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1925 if (LHSIt->start < RHSIt->start) {
1926 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1927 if (LHSIt != LHS.begin()) --LHSIt;
1928 } else if (RHSIt->start < LHSIt->start) {
1929 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1930 if (RHSIt != RHS.begin()) --RHSIt;
1933 SmallVector<VNInfo*, 8> EliminatedLHSVals;
1936 // Determine if these live intervals overlap.
1937 bool Overlaps = false;
1938 if (LHSIt->start <= RHSIt->start)
1939 Overlaps = LHSIt->end > RHSIt->start;
1941 Overlaps = RHSIt->end > LHSIt->start;
1943 // If the live intervals overlap, there are two interesting cases: if the
1944 // LHS interval is defined by a copy from the RHS, it's ok and we record
1945 // that the LHS value # is the same as the RHS. If it's not, then we cannot
1946 // coalesce these live ranges and we bail out.
1948 // If we haven't already recorded that this value # is safe, check it.
1949 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
1950 // If it's re-defined by an early clobber somewhere in the live range,
1951 // then conservatively abort coalescing.
1952 if (LHSIt->valno->hasRedefByEC())
1954 // Copy from the RHS?
1955 if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
1956 return false; // Nope, bail out.
1958 if (ValueLiveAt(LHSIt, LHS.end(), RHSIt->valno->def))
1959 // Here is an interesting situation:
1961 // vr1025 = copy vr1024
1966 // Even though vr1025 is copied from vr1024, it's not safe to
1967 // coalesce them since the live range of vr1025 intersects the
1968 // def of vr1024. This happens because vr1025 is assigned the
1969 // value of the previous iteration of vr1024.
1971 EliminatedLHSVals.push_back(LHSIt->valno);
1974 // We know this entire LHS live range is okay, so skip it now.
1975 if (++LHSIt == LHSEnd) break;
1979 if (LHSIt->end < RHSIt->end) {
1980 if (++LHSIt == LHSEnd) break;
1982 // One interesting case to check here. It's possible that we have
1983 // something like "X3 = Y" which defines a new value number in the LHS,
1984 // and is the last use of this liverange of the RHS. In this case, we
1985 // want to notice this copy (so that it gets coalesced away) even though
1986 // the live ranges don't actually overlap.
1987 if (LHSIt->start == RHSIt->end) {
1988 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
1989 // We already know that this value number is going to be merged in
1990 // if coalescing succeeds. Just skip the liverange.
1991 if (++LHSIt == LHSEnd) break;
1993 // If it's re-defined by an early clobber somewhere in the live range,
1994 // then conservatively abort coalescing.
1995 if (LHSIt->valno->hasRedefByEC())
1997 // Otherwise, if this is a copy from the RHS, mark it as being merged
1999 if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
2000 if (ValueLiveAt(LHSIt, LHS.end(), RHSIt->valno->def))
2001 // Here is an interesting situation:
2003 // vr1025 = copy vr1024
2008 // Even though vr1025 is copied from vr1024, it's not safe to
2009 // coalesced them since live range of vr1025 intersects the
2010 // def of vr1024. This happens because vr1025 is assigned the
2011 // value of the previous iteration of vr1024.
2013 EliminatedLHSVals.push_back(LHSIt->valno);
2015 // We know this entire LHS live range is okay, so skip it now.
2016 if (++LHSIt == LHSEnd) break;
2021 if (++RHSIt == RHSEnd) break;
2025 // If we got here, we know that the coalescing will be successful and that
2026 // the value numbers in EliminatedLHSVals will all be merged together. Since
2027 // the most common case is that EliminatedLHSVals has a single number, we
2028 // optimize for it: if there is more than one value, we merge them all into
2029 // the lowest numbered one, then handle the interval as if we were merging
2030 // with one value number.
2031 VNInfo *LHSValNo = NULL;
2032 if (EliminatedLHSVals.size() > 1) {
2033 // Loop through all the equal value numbers merging them into the smallest
2035 VNInfo *Smallest = EliminatedLHSVals[0];
2036 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
2037 if (EliminatedLHSVals[i]->id < Smallest->id) {
2038 // Merge the current notion of the smallest into the smaller one.
2039 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
2040 Smallest = EliminatedLHSVals[i];
2042 // Merge into the smallest.
2043 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
2046 LHSValNo = Smallest;
2047 } else if (EliminatedLHSVals.empty()) {
2048 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
2049 *tri_->getSuperRegisters(LHS.reg))
2050 // Imprecise sub-register information. Can't handle it.
2052 llvm_unreachable("No copies from the RHS?");
2054 LHSValNo = EliminatedLHSVals[0];
2057 // Okay, now that there is a single LHS value number that we're merging the
2058 // RHS into, update the value number info for the LHS to indicate that the
2059 // value number is defined where the RHS value number was.
2060 const VNInfo *VNI = RHS.getValNumInfo(0);
2061 LHSValNo->def = VNI->def;
2062 LHSValNo->setCopy(VNI->getCopy());
2064 // Okay, the final step is to loop over the RHS live intervals, adding them to
2066 if (VNI->hasPHIKill())
2067 LHSValNo->setHasPHIKill(true);
2068 LHS.addKills(LHSValNo, VNI->kills);
2069 LHS.MergeRangesInAsValue(RHS, LHSValNo);
2071 LHS.ComputeJoinedWeight(RHS);
2073 // Update regalloc hint if both are virtual registers.
2074 if (TargetRegisterInfo::isVirtualRegister(LHS.reg) &&
2075 TargetRegisterInfo::isVirtualRegister(RHS.reg)) {
2076 std::pair<unsigned, unsigned> RHSPref = mri_->getRegAllocationHint(RHS.reg);
2077 std::pair<unsigned, unsigned> LHSPref = mri_->getRegAllocationHint(LHS.reg);
2078 if (RHSPref != LHSPref)
2079 mri_->setRegAllocationHint(LHS.reg, RHSPref.first, RHSPref.second);
2082 // Update the liveintervals of sub-registers.
2083 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg))
2084 for (const unsigned *AS = tri_->getSubRegisters(LHS.reg); *AS; ++AS)
2085 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*li_, LHS,
2086 li_->getVNInfoAllocator());
2091 /// JoinIntervals - Attempt to join these two intervals. On failure, this
2092 /// returns false. Otherwise, if one of the intervals being joined is a
2093 /// physreg, this method always canonicalizes LHS to be it. The output
2094 /// "RHS" will not have been modified, so we can use this information
2095 /// below to update aliases.
2097 SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS,
2099 // Compute the final value assignment, assuming that the live ranges can be
2101 SmallVector<int, 16> LHSValNoAssignments;
2102 SmallVector<int, 16> RHSValNoAssignments;
2103 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
2104 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
2105 SmallVector<VNInfo*, 16> NewVNInfo;
2107 // If a live interval is a physical register, conservatively check if any
2108 // of its sub-registers is overlapping the live interval of the virtual
2109 // register. If so, do not coalesce.
2110 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
2111 *tri_->getSubRegisters(LHS.reg)) {
2112 // If it's coalescing a virtual register to a physical register, estimate
2113 // its live interval length. This is the *cost* of scanning an entire live
2114 // interval. If the cost is low, we'll do an exhaustive check instead.
2116 // If this is something like this:
2124 // That is, the live interval of v1024 crosses a bb. Then we can't rely on
2125 // less conservative check. It's possible a sub-register is defined before
2126 // v1024 (or live in) and live out of BB1.
2127 if (RHS.containsOneValue() &&
2128 li_->intervalIsInOneMBB(RHS) &&
2129 li_->getApproximateInstructionCount(RHS) <= 10) {
2130 // Perform a more exhaustive check for some common cases.
2131 if (li_->conflictsWithPhysRegRef(RHS, LHS.reg, true, JoinedCopies))
2134 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
2135 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
2137 errs() << "Interfere with sub-register ";
2138 li_->getInterval(*SR).print(errs(), tri_);
2143 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
2144 *tri_->getSubRegisters(RHS.reg)) {
2145 if (LHS.containsOneValue() &&
2146 li_->getApproximateInstructionCount(LHS) <= 10) {
2147 // Perform a more exhaustive check for some common cases.
2148 if (li_->conflictsWithPhysRegRef(LHS, RHS.reg, false, JoinedCopies))
2151 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
2152 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
2154 errs() << "Interfere with sub-register ";
2155 li_->getInterval(*SR).print(errs(), tri_);
2162 // Compute ultimate value numbers for the LHS and RHS values.
2163 if (RHS.containsOneValue()) {
2164 // Copies from a liveinterval with a single value are simple to handle and
2165 // very common, handle the special case here. This is important, because
2166 // often RHS is small and LHS is large (e.g. a physreg).
2168 // Find out if the RHS is defined as a copy from some value in the LHS.
2169 int RHSVal0DefinedFromLHS = -1;
2171 VNInfo *RHSValNoInfo = NULL;
2172 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
2173 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
2174 if (RHSSrcReg == 0 || RHSSrcReg != LHS.reg) {
2175 // If RHS is not defined as a copy from the LHS, we can use simpler and
2176 // faster checks to see if the live ranges are coalescable. This joiner
2177 // can't swap the LHS/RHS intervals though.
2178 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2179 return SimpleJoin(LHS, RHS);
2181 RHSValNoInfo = RHSValNoInfo0;
2184 // It was defined as a copy from the LHS, find out what value # it is.
2186 LHS.getLiveRangeContaining(RHSValNoInfo0->def.getPrevSlot())->valno;
2187 RHSValID = RHSValNoInfo->id;
2188 RHSVal0DefinedFromLHS = RHSValID;
2191 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2192 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2193 NewVNInfo.resize(LHS.getNumValNums(), NULL);
2195 // Okay, *all* of the values in LHS that are defined as a copy from RHS
2196 // should now get updated.
2197 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2200 unsigned VN = VNI->id;
2201 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
2202 if (LHSSrcReg != RHS.reg) {
2203 // If this is not a copy from the RHS, its value number will be
2204 // unmodified by the coalescing.
2205 NewVNInfo[VN] = VNI;
2206 LHSValNoAssignments[VN] = VN;
2207 } else if (RHSValID == -1) {
2208 // Otherwise, it is a copy from the RHS, and we don't already have a
2209 // value# for it. Keep the current value number, but remember it.
2210 LHSValNoAssignments[VN] = RHSValID = VN;
2211 NewVNInfo[VN] = RHSValNoInfo;
2212 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
2214 // Otherwise, use the specified value #.
2215 LHSValNoAssignments[VN] = RHSValID;
2216 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
2217 NewVNInfo[VN] = RHSValNoInfo;
2218 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
2222 NewVNInfo[VN] = VNI;
2223 LHSValNoAssignments[VN] = VN;
2227 assert(RHSValID != -1 && "Didn't find value #?");
2228 RHSValNoAssignments[0] = RHSValID;
2229 if (RHSVal0DefinedFromLHS != -1) {
2230 // This path doesn't go through ComputeUltimateVN so just set
2232 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
2235 // Loop over the value numbers of the LHS, seeing if any are defined from
2237 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2240 if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy?
2243 // DstReg is known to be a register in the LHS interval. If the src is
2244 // from the RHS interval, we can use its value #.
2245 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
2248 // Figure out the value # from the RHS.
2249 LHSValsDefinedFromRHS[VNI]=
2250 RHS.getLiveRangeContaining(VNI->def.getPrevSlot())->valno;
2253 // Loop over the value numbers of the RHS, seeing if any are defined from
2255 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2258 if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy?
2261 // DstReg is known to be a register in the RHS interval. If the src is
2262 // from the LHS interval, we can use its value #.
2263 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
2266 // Figure out the value # from the LHS.
2267 RHSValsDefinedFromLHS[VNI]=
2268 LHS.getLiveRangeContaining(VNI->def.getPrevSlot())->valno;
2271 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2272 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2273 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
2275 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2278 unsigned VN = VNI->id;
2279 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
2281 ComputeUltimateVN(VNI, NewVNInfo,
2282 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
2283 LHSValNoAssignments, RHSValNoAssignments);
2285 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2288 unsigned VN = VNI->id;
2289 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
2291 // If this value number isn't a copy from the LHS, it's a new number.
2292 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
2293 NewVNInfo.push_back(VNI);
2294 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
2298 ComputeUltimateVN(VNI, NewVNInfo,
2299 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
2300 RHSValNoAssignments, LHSValNoAssignments);
2304 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
2305 // interval lists to see if these intervals are coalescable.
2306 LiveInterval::const_iterator I = LHS.begin();
2307 LiveInterval::const_iterator IE = LHS.end();
2308 LiveInterval::const_iterator J = RHS.begin();
2309 LiveInterval::const_iterator JE = RHS.end();
2311 // Skip ahead until the first place of potential sharing.
2312 if (I->start < J->start) {
2313 I = std::upper_bound(I, IE, J->start);
2314 if (I != LHS.begin()) --I;
2315 } else if (J->start < I->start) {
2316 J = std::upper_bound(J, JE, I->start);
2317 if (J != RHS.begin()) --J;
2321 // Determine if these two live ranges overlap.
2323 if (I->start < J->start) {
2324 Overlaps = I->end > J->start;
2326 Overlaps = J->end > I->start;
2329 // If so, check value # info to determine if they are really different.
2331 // If the live range overlap will map to the same value number in the
2332 // result liverange, we can still coalesce them. If not, we can't.
2333 if (LHSValNoAssignments[I->valno->id] !=
2334 RHSValNoAssignments[J->valno->id])
2336 // If it's re-defined by an early clobber somewhere in the live range,
2337 // then conservatively abort coalescing.
2338 if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
2342 if (I->end < J->end) {
2351 // Update kill info. Some live ranges are extended due to copy coalescing.
2352 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
2353 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
2354 VNInfo *VNI = I->first;
2355 unsigned LHSValID = LHSValNoAssignments[VNI->id];
2356 NewVNInfo[LHSValID]->removeKill(VNI->def);
2357 if (VNI->hasPHIKill())
2358 NewVNInfo[LHSValID]->setHasPHIKill(true);
2359 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
2362 // Update kill info. Some live ranges are extended due to copy coalescing.
2363 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
2364 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
2365 VNInfo *VNI = I->first;
2366 unsigned RHSValID = RHSValNoAssignments[VNI->id];
2367 NewVNInfo[RHSValID]->removeKill(VNI->def);
2368 if (VNI->hasPHIKill())
2369 NewVNInfo[RHSValID]->setHasPHIKill(true);
2370 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
2373 // If we get here, we know that we can coalesce the live ranges. Ask the
2374 // intervals to coalesce themselves now.
2375 if ((RHS.ranges.size() > LHS.ranges.size() &&
2376 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
2377 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2378 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo,
2382 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
2390 // DepthMBBCompare - Comparison predicate that sort first based on the loop
2391 // depth of the basic block (the unsigned), and then on the MBB number.
2392 struct DepthMBBCompare {
2393 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
2394 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
2395 // Deeper loops first
2396 if (LHS.first != RHS.first)
2397 return LHS.first > RHS.first;
2399 // Prefer blocks that are more connected in the CFG. This takes care of
2400 // the most difficult copies first while intervals are short.
2401 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
2402 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
2406 // As a last resort, sort by block number.
2407 return LHS.second->getNumber() < RHS.second->getNumber();
2412 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
2413 std::vector<CopyRec> &TryAgain) {
2414 DEBUG(errs() << MBB->getName() << ":\n");
2416 std::vector<CopyRec> VirtCopies;
2417 std::vector<CopyRec> PhysCopies;
2418 std::vector<CopyRec> ImpDefCopies;
2419 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2421 MachineInstr *Inst = MII++;
2423 // If this isn't a copy nor a extract_subreg, we can't join intervals.
2424 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2425 bool isInsUndef = false;
2426 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
2427 DstReg = Inst->getOperand(0).getReg();
2428 SrcReg = Inst->getOperand(1).getReg();
2429 } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
2430 DstReg = Inst->getOperand(0).getReg();
2431 SrcReg = Inst->getOperand(2).getReg();
2432 if (Inst->getOperand(1).isUndef())
2434 } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
2435 Inst->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
2436 DstReg = Inst->getOperand(0).getReg();
2437 SrcReg = Inst->getOperand(2).getReg();
2438 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
2441 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
2442 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
2444 (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty()))
2445 ImpDefCopies.push_back(CopyRec(Inst, 0));
2446 else if (SrcIsPhys || DstIsPhys)
2447 PhysCopies.push_back(CopyRec(Inst, 0));
2449 VirtCopies.push_back(CopyRec(Inst, 0));
2452 // Try coalescing implicit copies and insert_subreg <undef> first,
2453 // followed by copies to / from physical registers, then finally copies
2454 // from virtual registers to virtual registers.
2455 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
2456 CopyRec &TheCopy = ImpDefCopies[i];
2458 if (!JoinCopy(TheCopy, Again))
2460 TryAgain.push_back(TheCopy);
2462 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
2463 CopyRec &TheCopy = PhysCopies[i];
2465 if (!JoinCopy(TheCopy, Again))
2467 TryAgain.push_back(TheCopy);
2469 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
2470 CopyRec &TheCopy = VirtCopies[i];
2472 if (!JoinCopy(TheCopy, Again))
2474 TryAgain.push_back(TheCopy);
2478 void SimpleRegisterCoalescing::joinIntervals() {
2479 DEBUG(errs() << "********** JOINING INTERVALS ***********\n");
2481 std::vector<CopyRec> TryAgainList;
2482 if (loopInfo->empty()) {
2483 // If there are no loops in the function, join intervals in function order.
2484 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
2486 CopyCoalesceInMBB(I, TryAgainList);
2488 // Otherwise, join intervals in inner loops before other intervals.
2489 // Unfortunately we can't just iterate over loop hierarchy here because
2490 // there may be more MBB's than BB's. Collect MBB's for sorting.
2492 // Join intervals in the function prolog first. We want to join physical
2493 // registers with virtual registers before the intervals got too long.
2494 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
2495 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
2496 MachineBasicBlock *MBB = I;
2497 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
2500 // Sort by loop depth.
2501 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2503 // Finally, join intervals in loop nest order.
2504 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2505 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
2508 // Joining intervals can allow other intervals to be joined. Iteratively join
2509 // until we make no progress.
2510 bool ProgressMade = true;
2511 while (ProgressMade) {
2512 ProgressMade = false;
2514 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
2515 CopyRec &TheCopy = TryAgainList[i];
2520 bool Success = JoinCopy(TheCopy, Again);
2521 if (Success || !Again) {
2522 TheCopy.MI = 0; // Mark this one as done.
2523 ProgressMade = true;
2529 /// Return true if the two specified registers belong to different register
2530 /// classes. The registers may be either phys or virt regs.
2532 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
2533 unsigned RegB) const {
2534 // Get the register classes for the first reg.
2535 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
2536 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
2537 "Shouldn't consider two physregs!");
2538 return !mri_->getRegClass(RegB)->contains(RegA);
2541 // Compare against the regclass for the second reg.
2542 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
2543 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
2544 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
2545 return RegClassA != RegClassB;
2547 return !RegClassA->contains(RegB);
2550 /// lastRegisterUse - Returns the last use of the specific register between
2551 /// cycles Start and End or NULL if there are no uses.
2553 SimpleRegisterCoalescing::lastRegisterUse(SlotIndex Start,
2556 SlotIndex &UseIdx) const{
2557 UseIdx = SlotIndex();
2558 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2559 MachineOperand *LastUse = NULL;
2560 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
2561 E = mri_->use_end(); I != E; ++I) {
2562 MachineOperand &Use = I.getOperand();
2563 MachineInstr *UseMI = Use.getParent();
2564 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2565 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2567 // Ignore identity copies.
2569 SlotIndex Idx = li_->getInstructionIndex(UseMI);
2570 // FIXME: Should this be Idx != UseIdx? SlotIndex() will return something
2571 // that compares higher than any other interval.
2572 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
2574 UseIdx = Idx.getUseIndex();
2580 SlotIndex s = Start;
2581 SlotIndex e = End.getPrevSlot().getBaseIndex();
2583 // Skip deleted instructions
2584 MachineInstr *MI = li_->getInstructionFromIndex(e);
2585 while (e != SlotIndex() && e.getPrevIndex() >= s && !MI) {
2586 e = e.getPrevIndex();
2587 MI = li_->getInstructionFromIndex(e);
2589 if (e < s || MI == NULL)
2592 // Ignore identity copies.
2593 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2594 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2596 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2597 MachineOperand &Use = MI->getOperand(i);
2598 if (Use.isReg() && Use.isUse() && Use.getReg() &&
2599 tri_->regsOverlap(Use.getReg(), Reg)) {
2600 UseIdx = e.getUseIndex();
2605 e = e.getPrevIndex();
2612 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
2613 if (TargetRegisterInfo::isPhysicalRegister(reg))
2614 errs() << tri_->getName(reg);
2616 errs() << "%reg" << reg;
2619 void SimpleRegisterCoalescing::releaseMemory() {
2620 JoinedCopies.clear();
2621 ReMatCopies.clear();
2625 /// Returns true if the given live interval is zero length.
2626 static bool isZeroLengthInterval(LiveInterval *li, LiveIntervals *li_) {
2627 for (LiveInterval::Ranges::const_iterator
2628 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
2629 if (i->end.getPrevIndex() > i->start)
2635 void SimpleRegisterCoalescing::CalculateSpillWeights() {
2636 SmallSet<unsigned, 4> Processed;
2637 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2638 mbbi != mbbe; ++mbbi) {
2639 MachineBasicBlock* MBB = mbbi;
2640 SlotIndex MBBEnd = li_->getMBBEndIdx(MBB);
2641 MachineLoop* loop = loopInfo->getLoopFor(MBB);
2642 unsigned loopDepth = loop ? loop->getLoopDepth() : 0;
2643 bool isExiting = loop ? loop->isLoopExiting(MBB) : false;
2645 for (MachineBasicBlock::const_iterator mii = MBB->begin(), mie = MBB->end();
2646 mii != mie; ++mii) {
2647 const MachineInstr *MI = mii;
2648 if (tii_->isIdentityCopy(*MI))
2651 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
2654 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2655 const MachineOperand &mopi = MI->getOperand(i);
2656 if (!mopi.isReg() || mopi.getReg() == 0)
2658 unsigned Reg = mopi.getReg();
2659 if (!TargetRegisterInfo::isVirtualRegister(mopi.getReg()))
2661 // Multiple uses of reg by the same instruction. It should not
2662 // contribute to spill weight again.
2663 if (!Processed.insert(Reg))
2666 bool HasDef = mopi.isDef();
2667 bool HasUse = !HasDef;
2668 for (unsigned j = i+1; j != e; ++j) {
2669 const MachineOperand &mopj = MI->getOperand(j);
2670 if (!mopj.isReg() || mopj.getReg() != Reg)
2672 HasDef |= mopj.isDef();
2673 HasUse |= mopj.isUse();
2674 if (HasDef && HasUse)
2678 LiveInterval &RegInt = li_->getInterval(Reg);
2679 float Weight = li_->getSpillWeight(HasDef, HasUse, loopDepth);
2680 if (HasDef && isExiting) {
2681 // Looks like this is a loop count variable update.
2682 SlotIndex DefIdx = li_->getInstructionIndex(MI).getDefIndex();
2683 const LiveRange *DLR =
2684 li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
2685 if (DLR->end > MBBEnd)
2688 RegInt.weight += Weight;
2694 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
2695 LiveInterval &LI = *I->second;
2696 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
2697 // If the live interval length is essentially zero, i.e. in every live
2698 // range the use follows def immediately, it doesn't make sense to spill
2699 // it and hope it will be easier to allocate for this li.
2700 if (isZeroLengthInterval(&LI, li_)) {
2701 LI.weight = HUGE_VALF;
2705 bool isLoad = false;
2706 SmallVector<LiveInterval*, 4> SpillIs;
2707 if (li_->isReMaterializable(LI, SpillIs, isLoad)) {
2708 // If all of the definitions of the interval are re-materializable,
2709 // it is a preferred candidate for spilling. If non of the defs are
2710 // loads, then it's potentially very cheap to re-materialize.
2711 // FIXME: this gets much more complicated once we support non-trivial
2712 // re-materialization.
2719 // Slightly prefer live interval that has been assigned a preferred reg.
2720 std::pair<unsigned, unsigned> Hint = mri_->getRegAllocationHint(LI.reg);
2721 if (Hint.first || Hint.second)
2724 // Divide the weight of the interval by its size. This encourages
2725 // spilling of intervals that are large and have few uses, and
2726 // discourages spilling of small intervals with many uses.
2727 LI.weight /= li_->getApproximateInstructionCount(LI) * InstrSlots::NUM;
2733 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2735 mri_ = &fn.getRegInfo();
2736 tm_ = &fn.getTarget();
2737 tri_ = tm_->getRegisterInfo();
2738 tii_ = tm_->getInstrInfo();
2739 li_ = &getAnalysis<LiveIntervals>();
2740 AA = &getAnalysis<AliasAnalysis>();
2741 loopInfo = &getAnalysis<MachineLoopInfo>();
2743 DEBUG(errs() << "********** SIMPLE REGISTER COALESCING **********\n"
2744 << "********** Function: "
2745 << ((Value*)mf_->getFunction())->getName() << '\n');
2747 allocatableRegs_ = tri_->getAllocatableSet(fn);
2748 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2749 E = tri_->regclass_end(); I != E; ++I)
2750 allocatableRCRegs_.insert(std::make_pair(*I,
2751 tri_->getAllocatableSet(fn, *I)));
2753 // Join (coalesce) intervals if requested.
2754 if (EnableJoining) {
2757 errs() << "********** INTERVALS POST JOINING **********\n";
2758 for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
2760 I->second->print(errs(), tri_);
2766 // Perform a final pass over the instructions and compute spill weights
2767 // and remove identity moves.
2768 SmallVector<unsigned, 4> DeadDefs;
2769 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2770 mbbi != mbbe; ++mbbi) {
2771 MachineBasicBlock* mbb = mbbi;
2772 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2774 MachineInstr *MI = mii;
2775 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2776 if (JoinedCopies.count(MI)) {
2777 // Delete all coalesced copies.
2778 bool DoDelete = true;
2779 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
2780 assert((MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
2781 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
2782 MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) &&
2783 "Unrecognized copy instruction");
2784 DstReg = MI->getOperand(0).getReg();
2785 if (TargetRegisterInfo::isPhysicalRegister(DstReg))
2786 // Do not delete extract_subreg, insert_subreg of physical
2787 // registers unless the definition is dead. e.g.
2788 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
2789 // or else the scavenger may complain. LowerSubregs will
2790 // delete them later.
2793 if (MI->registerDefIsDead(DstReg)) {
2794 LiveInterval &li = li_->getInterval(DstReg);
2795 if (!ShortenDeadCopySrcLiveRange(li, MI))
2796 ShortenDeadCopyLiveRange(li, MI);
2800 mii = llvm::next(mii);
2802 li_->RemoveMachineInstrFromMaps(MI);
2803 mii = mbbi->erase(mii);
2809 // Now check if this is a remat'ed def instruction which is now dead.
2810 if (ReMatDefs.count(MI)) {
2812 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2813 const MachineOperand &MO = MI->getOperand(i);
2816 unsigned Reg = MO.getReg();
2819 if (TargetRegisterInfo::isVirtualRegister(Reg))
2820 DeadDefs.push_back(Reg);
2823 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
2824 !mri_->use_empty(Reg)) {
2830 while (!DeadDefs.empty()) {
2831 unsigned DeadDef = DeadDefs.back();
2832 DeadDefs.pop_back();
2833 RemoveDeadDef(li_->getInterval(DeadDef), MI);
2835 li_->RemoveMachineInstrFromMaps(mii);
2836 mii = mbbi->erase(mii);
2842 // If the move will be an identity move delete it
2843 bool isMove= tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
2844 if (isMove && SrcReg == DstReg) {
2845 if (li_->hasInterval(SrcReg)) {
2846 LiveInterval &RegInt = li_->getInterval(SrcReg);
2847 // If def of this move instruction is dead, remove its live range
2848 // from the dstination register's live interval.
2849 if (MI->registerDefIsDead(DstReg)) {
2850 if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
2851 ShortenDeadCopyLiveRange(RegInt, MI);
2854 li_->RemoveMachineInstrFromMaps(MI);
2855 mii = mbbi->erase(mii);
2863 CalculateSpillWeights();
2869 /// print - Implement the dump method.
2870 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
2874 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2875 return new SimpleRegisterCoalescing();
2878 // Make sure that anything that uses RegisterCoalescer pulls in this file...
2879 DEFINING_FILE_FOR(SimpleRegisterCoalescing)