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 dbgs() << "Interfere with sub-register ";
187 li_->getInterval(*SR).print(dbgs(), tri_);
194 dbgs() << "\nExtending: ";
195 IntB.print(dbgs(), 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 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 dbgs() << " result = ";
228 IntB.print(dbgs(), 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_nodbg_iterator UI =
379 mri_->use_nodbg_begin(IntA.reg),
380 UE = mri_->use_nodbg_end(); UI != UE; ++UI) {
381 MachineInstr *UseMI = &*UI;
382 SlotIndex UseIdx = li_->getInstructionIndex(UseMI);
383 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
384 if (ULR == IntA.end())
386 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
390 // At this point we have decided that it is legal to do this
391 // transformation. Start by commuting the instruction.
392 MachineBasicBlock *MBB = DefMI->getParent();
393 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
396 if (NewMI != DefMI) {
397 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
398 MBB->insert(DefMI, NewMI);
401 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
402 NewMI->getOperand(OpIdx).setIsKill();
404 bool BHasPHIKill = BValNo->hasPHIKill();
405 SmallVector<VNInfo*, 4> BDeadValNos;
406 VNInfo::KillSet BKills;
407 std::map<SlotIndex, SlotIndex> BExtend;
409 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
418 // then do not add kills of A to the newly created B interval.
419 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
421 BExtend[ALR->end] = BLR->end;
423 // Update uses of IntA of the specific Val# with IntB.
424 bool BHasSubRegs = false;
425 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
426 BHasSubRegs = *tri_->getSubRegisters(IntB.reg);
427 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
428 UE = mri_->use_end(); UI != UE;) {
429 MachineOperand &UseMO = UI.getOperand();
430 MachineInstr *UseMI = &*UI;
432 if (JoinedCopies.count(UseMI))
434 if (UseMI->isDebugValue()) {
435 // FIXME These don't have an instruction index. Not clear we have enough
436 // info to decide whether to do this replacement or not. For now do it.
437 UseMO.setReg(NewReg);
440 SlotIndex UseIdx = li_->getInstructionIndex(UseMI).getUseIndex();
441 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
442 if (ULR == IntA.end() || ULR->valno != AValNo)
444 UseMO.setReg(NewReg);
447 if (UseMO.isKill()) {
449 UseMO.setIsKill(false);
451 BKills.push_back(UseIdx.getDefIndex());
453 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
454 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
456 if (DstReg == IntB.reg) {
457 // This copy will become a noop. If it's defining a new val#,
458 // remove that val# as well. However this live range is being
459 // extended to the end of the existing live range defined by the copy.
460 SlotIndex DefIdx = UseIdx.getDefIndex();
461 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
462 BHasPHIKill |= DLR->valno->hasPHIKill();
463 assert(DLR->valno->def == DefIdx);
464 BDeadValNos.push_back(DLR->valno);
465 BExtend[DLR->start] = DLR->end;
466 JoinedCopies.insert(UseMI);
467 // If this is a kill but it's going to be removed, the last use
468 // of the same val# is the new kill.
474 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
475 // simply extend BLR if CopyMI doesn't end the range.
477 dbgs() << "\nExtending: ";
478 IntB.print(dbgs(), tri_);
481 // Remove val#'s defined by copies that will be coalesced away.
482 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i) {
483 VNInfo *DeadVNI = BDeadValNos[i];
485 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
486 LiveInterval &SRLI = li_->getInterval(*SR);
487 const LiveRange *SRLR = SRLI.getLiveRangeContaining(DeadVNI->def);
488 SRLI.removeValNo(SRLR->valno);
491 IntB.removeValNo(BDeadValNos[i]);
494 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
495 // is updated. Kills are also updated.
496 VNInfo *ValNo = BValNo;
497 ValNo->def = AValNo->def;
499 for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) {
500 if (ValNo->kills[j] != BLR->end)
501 BKills.push_back(ValNo->kills[j]);
503 ValNo->kills.clear();
504 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
506 if (AI->valno != AValNo) continue;
507 SlotIndex End = AI->end;
508 std::map<SlotIndex, SlotIndex>::iterator
509 EI = BExtend.find(End);
510 if (EI != BExtend.end())
512 IntB.addRange(LiveRange(AI->start, End, ValNo));
514 // If the IntB live range is assigned to a physical register, and if that
515 // physreg has sub-registers, update their live intervals as well.
517 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
518 LiveInterval &SRLI = li_->getInterval(*SR);
519 SRLI.MergeInClobberRange(*li_, AI->start, End,
520 li_->getVNInfoAllocator());
524 IntB.addKills(ValNo, BKills);
525 ValNo->setHasPHIKill(BHasPHIKill);
528 dbgs() << " result = ";
529 IntB.print(dbgs(), tri_);
531 dbgs() << "\nShortening: ";
532 IntA.print(dbgs(), tri_);
535 IntA.removeValNo(AValNo);
538 dbgs() << " result = ";
539 IntA.print(dbgs(), tri_);
547 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
548 /// fallthoughs to SuccMBB.
549 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
550 MachineBasicBlock *SuccMBB,
551 const TargetInstrInfo *tii_) {
554 MachineBasicBlock *TBB = 0, *FBB = 0;
555 SmallVector<MachineOperand, 4> Cond;
556 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
557 MBB->isSuccessor(SuccMBB);
560 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
561 /// from a physical register live interval as well as from the live intervals
562 /// of its sub-registers.
563 static void removeRange(LiveInterval &li,
564 SlotIndex Start, SlotIndex End,
565 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
566 li.removeRange(Start, End, true);
567 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
568 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
569 if (!li_->hasInterval(*SR))
571 LiveInterval &sli = li_->getInterval(*SR);
572 SlotIndex RemoveStart = Start;
573 SlotIndex RemoveEnd = Start;
575 while (RemoveEnd != End) {
576 LiveInterval::iterator LR = sli.FindLiveRangeContaining(RemoveStart);
579 RemoveEnd = (LR->end < End) ? LR->end : End;
580 sli.removeRange(RemoveStart, RemoveEnd, true);
581 RemoveStart = RemoveEnd;
587 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
588 /// as the copy instruction, trim the live interval to the last use and return
591 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(SlotIndex CopyIdx,
592 MachineBasicBlock *CopyMBB,
594 const LiveRange *LR) {
595 SlotIndex MBBStart = li_->getMBBStartIdx(CopyMBB);
596 SlotIndex LastUseIdx;
597 MachineOperand *LastUse =
598 lastRegisterUse(LR->start, CopyIdx.getPrevSlot(), li.reg, LastUseIdx);
600 MachineInstr *LastUseMI = LastUse->getParent();
601 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
608 // r1025<dead> = r1024<kill>
609 if (MBBStart < LR->end)
610 removeRange(li, MBBStart, LR->end, li_, tri_);
614 // There are uses before the copy, just shorten the live range to the end
616 LastUse->setIsKill();
617 removeRange(li, LastUseIdx.getDefIndex(), LR->end, li_, tri_);
618 LR->valno->addKill(LastUseIdx.getDefIndex());
619 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
620 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
622 // Last use is itself an identity code.
623 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
624 LastUseMI->getOperand(DeadIdx).setIsDead();
630 if (LR->start <= MBBStart && LR->end > MBBStart) {
631 if (LR->start == li_->getZeroIndex()) {
632 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
633 // Live-in to the function but dead. Remove it from entry live-in set.
634 mf_->begin()->removeLiveIn(li.reg);
636 // FIXME: Shorten intervals in BBs that reaches this BB.
642 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
643 /// computation, replace the copy by rematerialize the definition.
644 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
647 MachineInstr *CopyMI) {
648 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getUseIndex();
649 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
650 assert(SrcLR != SrcInt.end() && "Live range not found!");
651 VNInfo *ValNo = SrcLR->valno;
652 // If other defs can reach uses of this def, then it's not safe to perform
653 // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
655 if (ValNo->isPHIDef() || !ValNo->isDefAccurate() ||
656 ValNo->isUnused() || ValNo->hasPHIKill())
658 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
659 const TargetInstrDesc &TID = DefMI->getDesc();
660 if (!TID.isAsCheapAsAMove())
662 if (!tii_->isTriviallyReMaterializable(DefMI, AA))
664 bool SawStore = false;
665 if (!DefMI->isSafeToMove(tii_, AA, SawStore))
667 if (TID.getNumDefs() != 1)
669 if (!DefMI->isImplicitDef()) {
670 // Make sure the copy destination register class fits the instruction
671 // definition register class. The mismatch can happen as a result of earlier
672 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
673 const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
674 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
675 if (mri_->getRegClass(DstReg) != RC)
677 } else if (!RC->contains(DstReg))
681 // If destination register has a sub-register index on it, make sure it mtches
682 // the instruction register class.
684 const TargetInstrDesc &TID = DefMI->getDesc();
685 if (TID.getNumDefs() != 1)
687 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
688 const TargetRegisterClass *DstSubRC =
689 DstRC->getSubRegisterRegClass(DstSubIdx);
690 const TargetRegisterClass *DefRC = TID.OpInfo[0].getRegClass(tri_);
693 else if (DefRC != DstSubRC)
697 SlotIndex DefIdx = CopyIdx.getDefIndex();
698 const LiveRange *DLR= li_->getInterval(DstReg).getLiveRangeContaining(DefIdx);
699 DLR->valno->setCopy(0);
700 // Don't forget to update sub-register intervals.
701 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
702 for (const unsigned* SR = tri_->getSubRegisters(DstReg); *SR; ++SR) {
703 if (!li_->hasInterval(*SR))
705 const LiveRange *DLR =
706 li_->getInterval(*SR).getLiveRangeContaining(DefIdx);
707 if (DLR && DLR->valno->getCopy() == CopyMI)
708 DLR->valno->setCopy(0);
712 // If copy kills the source register, find the last use and propagate
714 bool checkForDeadDef = false;
715 MachineBasicBlock *MBB = CopyMI->getParent();
716 if (CopyMI->killsRegister(SrcInt.reg))
717 if (!TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR)) {
718 checkForDeadDef = true;
721 MachineBasicBlock::iterator MII =
722 llvm::next(MachineBasicBlock::iterator(CopyMI));
723 tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI, tri_);
724 MachineInstr *NewMI = prior(MII);
726 if (checkForDeadDef) {
727 // PR4090 fix: Trim interval failed because there was no use of the
728 // source interval in this MBB. If the def is in this MBB too then we
729 // should mark it dead:
730 if (DefMI->getParent() == MBB) {
731 DefMI->addRegisterDead(SrcInt.reg, tri_);
732 SrcLR->end = SrcLR->start.getNextSlot();
736 // CopyMI may have implicit operands, transfer them over to the newly
737 // rematerialized instruction. And update implicit def interval valnos.
738 for (unsigned i = CopyMI->getDesc().getNumOperands(),
739 e = CopyMI->getNumOperands(); i != e; ++i) {
740 MachineOperand &MO = CopyMI->getOperand(i);
741 if (MO.isReg() && MO.isImplicit())
742 NewMI->addOperand(MO);
743 if (MO.isDef() && li_->hasInterval(MO.getReg())) {
744 unsigned Reg = MO.getReg();
745 const LiveRange *DLR =
746 li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
747 if (DLR && DLR->valno->getCopy() == CopyMI)
748 DLR->valno->setCopy(0);
749 // Handle subregs as well
750 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
751 for (const unsigned* SR = tri_->getSubRegisters(Reg); *SR; ++SR) {
752 if (!li_->hasInterval(*SR))
754 const LiveRange *DLR =
755 li_->getInterval(*SR).getLiveRangeContaining(DefIdx);
756 if (DLR && DLR->valno->getCopy() == CopyMI)
757 DLR->valno->setCopy(0);
763 TransferImplicitOps(CopyMI, NewMI);
764 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
765 CopyMI->eraseFromParent();
766 ReMatCopies.insert(CopyMI);
767 ReMatDefs.insert(DefMI);
768 DEBUG(dbgs() << "Remat: " << *NewMI);
773 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
774 /// update the subregister number if it is not zero. If DstReg is a
775 /// physical register and the existing subregister number of the def / use
776 /// being updated is not zero, make sure to set it to the correct physical
779 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
781 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
782 if (DstIsPhys && SubIdx) {
783 // Figure out the real physical register we are updating with.
784 DstReg = tri_->getSubReg(DstReg, SubIdx);
788 // Copy the register use-list before traversing it. We may be adding operands
789 // and invalidating pointers.
790 SmallVector<std::pair<MachineInstr*, unsigned>, 32> reglist;
791 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
792 E = mri_->reg_end(); I != E; ++I)
793 reglist.push_back(std::make_pair(&*I, I.getOperandNo()));
795 for (unsigned N=0; N != reglist.size(); ++N) {
796 MachineInstr *UseMI = reglist[N].first;
797 MachineOperand &O = UseMI->getOperand(reglist[N].second);
798 unsigned OldSubIdx = O.getSubReg();
800 unsigned UseDstReg = DstReg;
802 UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
804 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
805 if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
806 CopySrcSubIdx, CopyDstSubIdx) &&
807 CopySrcReg != CopyDstReg &&
808 CopySrcReg == SrcReg && CopyDstReg != UseDstReg) {
809 // If the use is a copy and it won't be coalesced away, and its source
810 // is defined by a trivial computation, try to rematerialize it instead.
811 if (ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg,
812 CopyDstSubIdx, UseMI))
819 // Def and kill of subregister of a virtual register actually defs and
820 // kills the whole register. Add imp-defs and imp-kills as needed.
823 UseMI->addRegisterDead(DstReg, tri_, true);
825 UseMI->addRegisterDefined(DstReg, tri_);
826 } else if (!O.isUndef() &&
828 UseMI->isRegTiedToDefOperand(&O-&UseMI->getOperand(0))))
829 UseMI->addRegisterKilled(DstReg, tri_, true);
834 // Sub-register indexes goes from small to large. e.g.
835 // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
836 // EAX: 1 -> AL, 2 -> AX
837 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
838 // sub-register 2 is also AX.
839 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
840 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
843 // Remove would-be duplicated kill marker.
844 if (O.isKill() && UseMI->killsRegister(DstReg))
848 // After updating the operand, check if the machine instruction has
849 // become a copy. If so, update its val# information.
850 if (JoinedCopies.count(UseMI))
853 const TargetInstrDesc &TID = UseMI->getDesc();
854 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
855 if (TID.getNumDefs() == 1 && TID.getNumOperands() > 2 &&
856 tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
857 CopySrcSubIdx, CopyDstSubIdx) &&
858 CopySrcReg != CopyDstReg &&
859 (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
860 allocatableRegs_[CopyDstReg])) {
861 LiveInterval &LI = li_->getInterval(CopyDstReg);
863 li_->getInstructionIndex(UseMI).getDefIndex();
864 if (const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx)) {
865 if (DLR->valno->def == DefIdx)
866 DLR->valno->setCopy(UseMI);
872 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
873 /// due to live range lengthening as the result of coalescing.
874 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
876 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
877 UE = mri_->use_end(); UI != UE; ++UI) {
878 MachineOperand &UseMO = UI.getOperand();
881 MachineInstr *UseMI = UseMO.getParent();
883 li_->getInstructionIndex(UseMI).getUseIndex();
884 const LiveRange *LR = LI.getLiveRangeContaining(UseIdx);
886 (!LR->valno->isKill(UseIdx.getDefIndex()) &&
887 LR->valno->def != UseIdx.getDefIndex())) {
888 // Interesting problem. After coalescing reg1027's def and kill are both
889 // at the same point: %reg1027,0.000000e+00 = [56,814:0) 0@70-(814)
892 // 60 %reg1027<def> = t2MOVr %reg1027, 14, %reg0, %reg0
893 // 68 %reg1027<def> = t2LDRi12 %reg1027<kill>, 8, 14, %reg0
894 // 76 t2CMPzri %reg1038<kill,undef>, 0, 14, %reg0, %CPSR<imp-def>
895 // 84 %reg1027<def> = t2MOVr %reg1027, 14, %reg0, %reg0
896 // 96 t2Bcc mbb<bb5,0x2030910>, 1, %CPSR<kill>
898 // Do not remove the kill marker on t2LDRi12.
899 UseMO.setIsKill(false);
904 /// removeIntervalIfEmpty - Check if the live interval of a physical register
905 /// is empty, if so remove it and also remove the empty intervals of its
906 /// sub-registers. Return true if live interval is removed.
907 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
908 const TargetRegisterInfo *tri_) {
910 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
911 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
912 if (!li_->hasInterval(*SR))
914 LiveInterval &sli = li_->getInterval(*SR);
916 li_->removeInterval(*SR);
918 li_->removeInterval(li.reg);
924 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
925 /// Return true if live interval is removed.
926 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
927 MachineInstr *CopyMI) {
928 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
929 LiveInterval::iterator MLR =
930 li.FindLiveRangeContaining(CopyIdx.getDefIndex());
932 return false; // Already removed by ShortenDeadCopySrcLiveRange.
933 SlotIndex RemoveStart = MLR->start;
934 SlotIndex RemoveEnd = MLR->end;
935 SlotIndex DefIdx = CopyIdx.getDefIndex();
936 // Remove the liverange that's defined by this.
937 if (RemoveStart == DefIdx && RemoveEnd == DefIdx.getStoreIndex()) {
938 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
939 return removeIntervalIfEmpty(li, li_, tri_);
944 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
945 /// the val# it defines. If the live interval becomes empty, remove it as well.
946 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
947 MachineInstr *DefMI) {
948 SlotIndex DefIdx = li_->getInstructionIndex(DefMI).getDefIndex();
949 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
950 if (DefIdx != MLR->valno->def)
952 li.removeValNo(MLR->valno);
953 return removeIntervalIfEmpty(li, li_, tri_);
956 /// PropagateDeadness - Propagate the dead marker to the instruction which
957 /// defines the val#.
958 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
959 SlotIndex &LRStart, LiveIntervals *li_,
960 const TargetRegisterInfo* tri_) {
961 MachineInstr *DefMI =
962 li_->getInstructionFromIndex(LRStart.getDefIndex());
963 if (DefMI && DefMI != CopyMI) {
964 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false);
966 DefMI->getOperand(DeadIdx).setIsDead();
968 DefMI->addOperand(MachineOperand::CreateReg(li.reg,
969 /*def*/true, /*implicit*/true, /*kill*/false, /*dead*/true));
970 LRStart = LRStart.getNextSlot();
974 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
975 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
976 /// ends the live range there. If there isn't another use, then this live range
977 /// is dead. Return true if live interval is removed.
979 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
980 MachineInstr *CopyMI) {
981 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
982 if (CopyIdx == SlotIndex()) {
983 // FIXME: special case: function live in. It can be a general case if the
984 // first instruction index starts at > 0 value.
985 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
986 // Live-in to the function but dead. Remove it from entry live-in set.
987 if (mf_->begin()->isLiveIn(li.reg))
988 mf_->begin()->removeLiveIn(li.reg);
989 const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
990 removeRange(li, LR->start, LR->end, li_, tri_);
991 return removeIntervalIfEmpty(li, li_, tri_);
994 LiveInterval::iterator LR =
995 li.FindLiveRangeContaining(CopyIdx.getPrevIndex().getStoreIndex());
997 // Livein but defined by a phi.
1000 SlotIndex RemoveStart = LR->start;
1001 SlotIndex RemoveEnd = CopyIdx.getStoreIndex();
1002 if (LR->end > RemoveEnd)
1003 // More uses past this copy? Nothing to do.
1006 // If there is a last use in the same bb, we can't remove the live range.
1007 // Shorten the live interval and return.
1008 MachineBasicBlock *CopyMBB = CopyMI->getParent();
1009 if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
1012 // There are other kills of the val#. Nothing to do.
1013 if (!li.isOnlyLROfValNo(LR))
1016 MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
1017 if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
1018 // If the live range starts in another mbb and the copy mbb is not a fall
1019 // through mbb, then we can only cut the range from the beginning of the
1021 RemoveStart = li_->getMBBStartIdx(CopyMBB).getNextIndex().getBaseIndex();
1023 if (LR->valno->def == RemoveStart) {
1024 // If the def MI defines the val# and this copy is the only kill of the
1025 // val#, then propagate the dead marker.
1026 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
1029 if (LR->valno->isKill(RemoveEnd))
1030 LR->valno->removeKill(RemoveEnd);
1033 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
1034 return removeIntervalIfEmpty(li, li_, tri_);
1037 /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
1038 /// from an implicit def to another register can be coalesced away.
1039 bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
1041 LiveInterval &ImpLi) const{
1042 if (!CopyMI->killsRegister(ImpLi.reg))
1044 // Make sure this is the only use.
1045 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(ImpLi.reg),
1046 UE = mri_->use_end(); UI != UE;) {
1047 MachineInstr *UseMI = &*UI;
1049 if (CopyMI == UseMI || JoinedCopies.count(UseMI))
1057 /// isWinToJoinVRWithSrcPhysReg - Return true if it's worth while to join a
1058 /// a virtual destination register with physical source register.
1060 SimpleRegisterCoalescing::isWinToJoinVRWithSrcPhysReg(MachineInstr *CopyMI,
1061 MachineBasicBlock *CopyMBB,
1062 LiveInterval &DstInt,
1063 LiveInterval &SrcInt) {
1064 // If the virtual register live interval is long but it has low use desity,
1065 // do not join them, instead mark the physical register as its allocation
1067 const TargetRegisterClass *RC = mri_->getRegClass(DstInt.reg);
1068 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1069 unsigned Length = li_->getApproximateInstructionCount(DstInt);
1070 if (Length > Threshold &&
1071 (((float)std::distance(mri_->use_nodbg_begin(DstInt.reg),
1072 mri_->use_nodbg_end()) / Length) <
1076 // If the virtual register live interval extends into a loop, turn down
1079 li_->getInstructionIndex(CopyMI).getDefIndex();
1080 const MachineLoop *L = loopInfo->getLoopFor(CopyMBB);
1082 // Let's see if the virtual register live interval extends into the loop.
1083 LiveInterval::iterator DLR = DstInt.FindLiveRangeContaining(CopyIdx);
1084 assert(DLR != DstInt.end() && "Live range not found!");
1085 DLR = DstInt.FindLiveRangeContaining(DLR->end.getNextSlot());
1086 if (DLR != DstInt.end()) {
1087 CopyMBB = li_->getMBBFromIndex(DLR->start);
1088 L = loopInfo->getLoopFor(CopyMBB);
1092 if (!L || Length <= Threshold)
1095 SlotIndex UseIdx = CopyIdx.getUseIndex();
1096 LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1097 MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1098 if (loopInfo->getLoopFor(SMBB) != L) {
1099 if (!loopInfo->isLoopHeader(CopyMBB))
1101 // If vr's live interval extends pass the loop header, do not join.
1102 for (MachineBasicBlock::succ_iterator SI = CopyMBB->succ_begin(),
1103 SE = CopyMBB->succ_end(); SI != SE; ++SI) {
1104 MachineBasicBlock *SuccMBB = *SI;
1105 if (SuccMBB == CopyMBB)
1107 if (DstInt.overlaps(li_->getMBBStartIdx(SuccMBB),
1108 li_->getMBBEndIdx(SuccMBB)))
1115 /// isWinToJoinVRWithDstPhysReg - Return true if it's worth while to join a
1116 /// copy from a virtual source register to a physical destination register.
1118 SimpleRegisterCoalescing::isWinToJoinVRWithDstPhysReg(MachineInstr *CopyMI,
1119 MachineBasicBlock *CopyMBB,
1120 LiveInterval &DstInt,
1121 LiveInterval &SrcInt) {
1122 // If the virtual register live interval is long but it has low use density,
1123 // do not join them, instead mark the physical register as its allocation
1125 const TargetRegisterClass *RC = mri_->getRegClass(SrcInt.reg);
1126 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1127 unsigned Length = li_->getApproximateInstructionCount(SrcInt);
1128 if (Length > Threshold &&
1129 (((float)std::distance(mri_->use_nodbg_begin(SrcInt.reg),
1130 mri_->use_nodbg_end()) / Length) <
1135 // Must be implicit_def.
1138 // If the virtual register live interval is defined or cross a loop, turn
1139 // down aggressiveness.
1141 li_->getInstructionIndex(CopyMI).getDefIndex();
1142 SlotIndex UseIdx = CopyIdx.getUseIndex();
1143 LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1144 assert(SLR != SrcInt.end() && "Live range not found!");
1145 SLR = SrcInt.FindLiveRangeContaining(SLR->start.getPrevSlot());
1146 if (SLR == SrcInt.end())
1148 MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1149 const MachineLoop *L = loopInfo->getLoopFor(SMBB);
1151 if (!L || Length <= Threshold)
1154 if (loopInfo->getLoopFor(CopyMBB) != L) {
1155 if (SMBB != L->getLoopLatch())
1157 // If vr's live interval is extended from before the loop latch, do not
1159 for (MachineBasicBlock::pred_iterator PI = SMBB->pred_begin(),
1160 PE = SMBB->pred_end(); PI != PE; ++PI) {
1161 MachineBasicBlock *PredMBB = *PI;
1162 if (PredMBB == SMBB)
1164 if (SrcInt.overlaps(li_->getMBBStartIdx(PredMBB),
1165 li_->getMBBEndIdx(PredMBB)))
1172 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
1173 /// two virtual registers from different register classes.
1175 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned LargeReg,
1177 unsigned Threshold) {
1178 // Then make sure the intervals are *short*.
1179 LiveInterval &LargeInt = li_->getInterval(LargeReg);
1180 LiveInterval &SmallInt = li_->getInterval(SmallReg);
1181 unsigned LargeSize = li_->getApproximateInstructionCount(LargeInt);
1182 unsigned SmallSize = li_->getApproximateInstructionCount(SmallInt);
1183 if (LargeSize > Threshold) {
1184 unsigned SmallUses = std::distance(mri_->use_nodbg_begin(SmallReg),
1185 mri_->use_nodbg_end());
1186 unsigned LargeUses = std::distance(mri_->use_nodbg_begin(LargeReg),
1187 mri_->use_nodbg_end());
1188 if (SmallUses*LargeSize < LargeUses*SmallSize)
1194 /// HasIncompatibleSubRegDefUse - If we are trying to coalesce a virtual
1195 /// register with a physical register, check if any of the virtual register
1196 /// operand is a sub-register use or def. If so, make sure it won't result
1197 /// in an illegal extract_subreg or insert_subreg instruction. e.g.
1198 /// vr1024 = extract_subreg vr1025, 1
1200 /// vr1024 = mov8rr AH
1201 /// If vr1024 is coalesced with AH, the extract_subreg is now illegal since
1202 /// AH does not have a super-reg whose sub-register 1 is AH.
1204 SimpleRegisterCoalescing::HasIncompatibleSubRegDefUse(MachineInstr *CopyMI,
1207 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(VirtReg),
1208 E = mri_->reg_end(); I != E; ++I) {
1209 MachineOperand &O = I.getOperand();
1212 MachineInstr *MI = &*I;
1213 if (MI == CopyMI || JoinedCopies.count(MI))
1215 unsigned SubIdx = O.getSubReg();
1216 if (SubIdx && !tri_->getSubReg(PhysReg, SubIdx))
1218 if (MI->isExtractSubreg()) {
1219 SubIdx = MI->getOperand(2).getImm();
1220 if (O.isUse() && !tri_->getSubReg(PhysReg, SubIdx))
1223 unsigned SrcReg = MI->getOperand(1).getReg();
1224 const TargetRegisterClass *RC =
1225 TargetRegisterInfo::isPhysicalRegister(SrcReg)
1226 ? tri_->getPhysicalRegisterRegClass(SrcReg)
1227 : mri_->getRegClass(SrcReg);
1228 if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
1232 if (MI->isInsertSubreg() || MI->isSubregToReg()) {
1233 SubIdx = MI->getOperand(3).getImm();
1234 if (VirtReg == MI->getOperand(0).getReg()) {
1235 if (!tri_->getSubReg(PhysReg, SubIdx))
1238 unsigned DstReg = MI->getOperand(0).getReg();
1239 const TargetRegisterClass *RC =
1240 TargetRegisterInfo::isPhysicalRegister(DstReg)
1241 ? tri_->getPhysicalRegisterRegClass(DstReg)
1242 : mri_->getRegClass(DstReg);
1243 if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
1252 /// CanJoinExtractSubRegToPhysReg - Return true if it's possible to coalesce
1253 /// an extract_subreg where dst is a physical register, e.g.
1254 /// cl = EXTRACT_SUBREG reg1024, 1
1256 SimpleRegisterCoalescing::CanJoinExtractSubRegToPhysReg(unsigned DstReg,
1257 unsigned SrcReg, unsigned SubIdx,
1258 unsigned &RealDstReg) {
1259 const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
1260 RealDstReg = tri_->getMatchingSuperReg(DstReg, SubIdx, RC);
1261 assert(RealDstReg && "Invalid extract_subreg instruction!");
1263 LiveInterval &RHS = li_->getInterval(SrcReg);
1264 // For this type of EXTRACT_SUBREG, conservatively
1265 // check if the live interval of the source register interfere with the
1266 // actual super physical register we are trying to coalesce with.
1267 if (li_->hasInterval(RealDstReg) &&
1268 RHS.overlaps(li_->getInterval(RealDstReg))) {
1270 dbgs() << "Interfere with register ";
1271 li_->getInterval(RealDstReg).print(dbgs(), tri_);
1273 return false; // Not coalescable
1275 for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
1276 // Do not check DstReg or its sub-register. JoinIntervals() will take care
1278 if (*SR != DstReg &&
1279 !tri_->isSubRegister(DstReg, *SR) &&
1280 li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1282 dbgs() << "Interfere with sub-register ";
1283 li_->getInterval(*SR).print(dbgs(), tri_);
1285 return false; // Not coalescable
1290 /// CanJoinInsertSubRegToPhysReg - Return true if it's possible to coalesce
1291 /// an insert_subreg where src is a physical register, e.g.
1292 /// reg1024 = INSERT_SUBREG reg1024, c1, 0
1294 SimpleRegisterCoalescing::CanJoinInsertSubRegToPhysReg(unsigned DstReg,
1295 unsigned SrcReg, unsigned SubIdx,
1296 unsigned &RealSrcReg) {
1297 const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
1298 RealSrcReg = tri_->getMatchingSuperReg(SrcReg, SubIdx, RC);
1299 assert(RealSrcReg && "Invalid extract_subreg instruction!");
1301 LiveInterval &LHS = li_->getInterval(DstReg);
1302 if (li_->hasInterval(RealSrcReg) &&
1303 LHS.overlaps(li_->getInterval(RealSrcReg))) {
1305 dbgs() << "Interfere with register ";
1306 li_->getInterval(RealSrcReg).print(dbgs(), tri_);
1308 return false; // Not coalescable
1310 for (const unsigned* SR = tri_->getSubRegisters(RealSrcReg); *SR; ++SR)
1311 // Do not check SrcReg or its sub-register. JoinIntervals() will take care
1313 if (*SR != SrcReg &&
1314 !tri_->isSubRegister(SrcReg, *SR) &&
1315 li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1317 dbgs() << "Interfere with sub-register ";
1318 li_->getInterval(*SR).print(dbgs(), tri_);
1320 return false; // Not coalescable
1325 /// getRegAllocPreference - Return register allocation preference register.
1327 static unsigned getRegAllocPreference(unsigned Reg, MachineFunction &MF,
1328 MachineRegisterInfo *MRI,
1329 const TargetRegisterInfo *TRI) {
1330 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1332 std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
1333 return TRI->ResolveRegAllocHint(Hint.first, Hint.second, MF);
1336 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1337 /// which are the src/dst of the copy instruction CopyMI. This returns true
1338 /// if the copy was successfully coalesced away. If it is not currently
1339 /// possible to coalesce this interval, but it may be possible if other
1340 /// things get coalesced, then it returns true by reference in 'Again'.
1341 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1342 MachineInstr *CopyMI = TheCopy.MI;
1345 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1346 return false; // Already done.
1348 DEBUG(dbgs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1350 unsigned SrcReg, DstReg, SrcSubIdx = 0, DstSubIdx = 0;
1351 bool isExtSubReg = CopyMI->isExtractSubreg();
1352 bool isInsSubReg = CopyMI->isInsertSubreg();
1353 bool isSubRegToReg = CopyMI->isSubregToReg();
1354 unsigned SubIdx = 0;
1356 DstReg = CopyMI->getOperand(0).getReg();
1357 DstSubIdx = CopyMI->getOperand(0).getSubReg();
1358 SrcReg = CopyMI->getOperand(1).getReg();
1359 SrcSubIdx = CopyMI->getOperand(2).getImm();
1360 } else if (isInsSubReg || isSubRegToReg) {
1361 DstReg = CopyMI->getOperand(0).getReg();
1362 DstSubIdx = CopyMI->getOperand(3).getImm();
1363 SrcReg = CopyMI->getOperand(2).getReg();
1364 SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1365 if (SrcSubIdx && SrcSubIdx != DstSubIdx) {
1366 // r1025 = INSERT_SUBREG r1025, r1024<2>, 2 Then r1024 has already been
1367 // coalesced to a larger register so the subreg indices cancel out.
1368 DEBUG(dbgs() << "\tSource of insert_subreg or subreg_to_reg is already "
1369 "coalesced to another register.\n");
1370 return false; // Not coalescable.
1372 } else if (tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
1373 if (SrcSubIdx && DstSubIdx && SrcSubIdx != DstSubIdx) {
1374 // e.g. %reg16404:1<def> = MOV8rr %reg16412:2<kill>
1376 return false; // Not coalescable.
1379 llvm_unreachable("Unrecognized copy instruction!");
1382 // If they are already joined we continue.
1383 if (SrcReg == DstReg) {
1384 DEBUG(dbgs() << "\tCopy already coalesced.\n");
1385 return false; // Not coalescable.
1388 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1389 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1391 // If they are both physical registers, we cannot join them.
1392 if (SrcIsPhys && DstIsPhys) {
1393 DEBUG(dbgs() << "\tCan not coalesce physregs.\n");
1394 return false; // Not coalescable.
1397 // We only join virtual registers with allocatable physical registers.
1398 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
1399 DEBUG(dbgs() << "\tSrc reg is unallocatable physreg.\n");
1400 return false; // Not coalescable.
1402 if (DstIsPhys && !allocatableRegs_[DstReg]) {
1403 DEBUG(dbgs() << "\tDst reg is unallocatable physreg.\n");
1404 return false; // Not coalescable.
1407 // Check that a physical source register is compatible with dst regclass
1409 unsigned SrcSubReg = SrcSubIdx ?
1410 tri_->getSubReg(SrcReg, SrcSubIdx) : SrcReg;
1411 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
1412 const TargetRegisterClass *DstSubRC = DstRC;
1414 DstSubRC = DstRC->getSubRegisterRegClass(DstSubIdx);
1415 assert(DstSubRC && "Illegal subregister index");
1416 if (!DstSubRC->contains(SrcSubReg)) {
1417 DEBUG(dbgs() << "\tIncompatible destination regclass: "
1418 << tri_->getName(SrcSubReg) << " not in "
1419 << DstSubRC->getName() << ".\n");
1420 return false; // Not coalescable.
1424 // Check that a physical dst register is compatible with source regclass
1426 unsigned DstSubReg = DstSubIdx ?
1427 tri_->getSubReg(DstReg, DstSubIdx) : DstReg;
1428 const TargetRegisterClass *SrcRC = mri_->getRegClass(SrcReg);
1429 const TargetRegisterClass *SrcSubRC = SrcRC;
1431 SrcSubRC = SrcRC->getSubRegisterRegClass(SrcSubIdx);
1432 assert(SrcSubRC && "Illegal subregister index");
1433 if (!SrcSubRC->contains(DstSubReg)) {
1434 DEBUG(dbgs() << "\tIncompatible source regclass: "
1435 << tri_->getName(DstSubReg) << " not in "
1436 << SrcSubRC->getName() << ".\n");
1438 return false; // Not coalescable.
1442 // Should be non-null only when coalescing to a sub-register class.
1443 bool CrossRC = false;
1444 const TargetRegisterClass *SrcRC= SrcIsPhys ? 0 : mri_->getRegClass(SrcReg);
1445 const TargetRegisterClass *DstRC= DstIsPhys ? 0 : mri_->getRegClass(DstReg);
1446 const TargetRegisterClass *NewRC = NULL;
1447 MachineBasicBlock *CopyMBB = CopyMI->getParent();
1448 unsigned RealDstReg = 0;
1449 unsigned RealSrcReg = 0;
1450 if (isExtSubReg || isInsSubReg || isSubRegToReg) {
1451 SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
1452 if (SrcIsPhys && isExtSubReg) {
1453 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
1454 // coalesced with AX.
1455 unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
1457 // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
1458 // coalesced to a larger register so the subreg indices cancel out.
1459 if (DstSubIdx != SubIdx) {
1460 DEBUG(dbgs() << "\t Sub-register indices mismatch.\n");
1461 return false; // Not coalescable.
1464 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
1466 } else if (DstIsPhys && (isInsSubReg || isSubRegToReg)) {
1467 // EAX = INSERT_SUBREG EAX, r1024, 0
1468 unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1470 // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
1471 // coalesced to a larger register so the subreg indices cancel out.
1472 if (SrcSubIdx != SubIdx) {
1473 DEBUG(dbgs() << "\t Sub-register indices mismatch.\n");
1474 return false; // Not coalescable.
1477 DstReg = tri_->getSubReg(DstReg, SubIdx);
1479 } else if ((DstIsPhys && isExtSubReg) ||
1480 (SrcIsPhys && (isInsSubReg || isSubRegToReg))) {
1481 if (!isSubRegToReg && CopyMI->getOperand(1).getSubReg()) {
1482 DEBUG(dbgs() << "\tSrc of extract_subreg already coalesced with reg"
1483 << " of a super-class.\n");
1484 return false; // Not coalescable.
1487 // FIXME: The following checks are somewhat conservative. Perhaps a better
1488 // way to implement this is to treat this as coalescing a vr with the
1489 // super physical register.
1491 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealDstReg))
1492 return false; // Not coalescable
1494 if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1495 return false; // Not coalescable
1499 unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
1500 : CopyMI->getOperand(2).getSubReg();
1502 if (OldSubIdx == SubIdx && !differingRegisterClasses(SrcReg, DstReg))
1503 // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
1504 // coalesced to a larger register so the subreg indices cancel out.
1505 // Also check if the other larger register is of the same register
1506 // class as the would be resulting register.
1509 DEBUG(dbgs() << "\t Sub-register indices mismatch.\n");
1510 return false; // Not coalescable.
1514 if (!DstIsPhys && !SrcIsPhys) {
1515 if (isInsSubReg || isSubRegToReg) {
1516 NewRC = tri_->getMatchingSuperRegClass(DstRC, SrcRC, SubIdx);
1517 } else // extract_subreg {
1518 NewRC = tri_->getMatchingSuperRegClass(SrcRC, DstRC, SubIdx);
1521 DEBUG(dbgs() << "\t Conflicting sub-register indices.\n");
1522 return false; // Not coalescable
1525 unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
1526 unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
1527 unsigned Limit= allocatableRCRegs_[mri_->getRegClass(SmallReg)].count();
1528 if (!isWinToJoinCrossClass(LargeReg, SmallReg, Limit)) {
1529 Again = true; // May be possible to coalesce later.
1534 } else if (differingRegisterClasses(SrcReg, DstReg)) {
1535 if (DisableCrossClassJoin)
1539 // FIXME: What if the result of a EXTRACT_SUBREG is then coalesced
1540 // with another? If it's the resulting destination register, then
1541 // the subidx must be propagated to uses (but only those defined
1542 // by the EXTRACT_SUBREG). If it's being coalesced into another
1543 // register, it should be safe because register is assumed to have
1544 // the register class of the super-register.
1546 // Process moves where one of the registers have a sub-register index.
1547 MachineOperand *DstMO = CopyMI->findRegisterDefOperand(DstReg);
1548 MachineOperand *SrcMO = CopyMI->findRegisterUseOperand(SrcReg);
1549 SubIdx = DstMO->getSubReg();
1551 if (SrcMO->getSubReg())
1552 // FIXME: can we handle this?
1554 // This is not an insert_subreg but it looks like one.
1555 // e.g. %reg1024:4 = MOV32rr %EAX
1558 if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1559 return false; // Not coalescable
1563 SubIdx = SrcMO->getSubReg();
1565 // This is not a extract_subreg but it looks like one.
1566 // e.g. %cl = MOV16rr %reg1024:1
1569 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx,RealDstReg))
1570 return false; // Not coalescable
1576 unsigned LargeReg = SrcReg;
1577 unsigned SmallReg = DstReg;
1579 // Now determine the register class of the joined register.
1581 if (SubIdx && DstRC && DstRC->isASubClass()) {
1582 // This is a move to a sub-register class. However, the source is a
1583 // sub-register of a larger register class. We don't know what should
1584 // the register class be. FIXME.
1588 if (!DstIsPhys && !SrcIsPhys)
1590 } else if (!SrcIsPhys && !DstIsPhys) {
1591 NewRC = getCommonSubClass(SrcRC, DstRC);
1593 DEBUG(dbgs() << "\tDisjoint regclasses: "
1594 << SrcRC->getName() << ", "
1595 << DstRC->getName() << ".\n");
1596 return false; // Not coalescable.
1598 if (DstRC->getSize() > SrcRC->getSize())
1599 std::swap(LargeReg, SmallReg);
1602 // If we are joining two virtual registers and the resulting register
1603 // class is more restrictive (fewer register, smaller size). Check if it's
1604 // worth doing the merge.
1605 if (!SrcIsPhys && !DstIsPhys &&
1606 (isExtSubReg || DstRC->isASubClass()) &&
1607 !isWinToJoinCrossClass(LargeReg, SmallReg,
1608 allocatableRCRegs_[NewRC].count())) {
1609 DEBUG(dbgs() << "\tSrc/Dest are different register classes: "
1610 << SrcRC->getName() << "/"
1611 << DstRC->getName() << " -> "
1612 << NewRC->getName() << ".\n");
1613 // Allow the coalescer to try again in case either side gets coalesced to
1614 // a physical register that's compatible with the other side. e.g.
1615 // r1024 = MOV32to32_ r1025
1616 // But later r1024 is assigned EAX then r1025 may be coalesced with EAX.
1617 Again = true; // May be possible to coalesce later.
1622 // Will it create illegal extract_subreg / insert_subreg?
1623 if (SrcIsPhys && HasIncompatibleSubRegDefUse(CopyMI, DstReg, SrcReg))
1625 if (DstIsPhys && HasIncompatibleSubRegDefUse(CopyMI, SrcReg, DstReg))
1628 LiveInterval &SrcInt = li_->getInterval(SrcReg);
1629 LiveInterval &DstInt = li_->getInterval(DstReg);
1630 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
1631 "Register mapping is horribly broken!");
1634 dbgs() << "\t\tInspecting "; SrcInt.print(dbgs(), tri_);
1635 dbgs() << " and "; DstInt.print(dbgs(), tri_);
1639 // Save a copy of the virtual register live interval. We'll manually
1640 // merge this into the "real" physical register live interval this is
1642 LiveInterval *SavedLI = 0;
1644 SavedLI = li_->dupInterval(&SrcInt);
1645 else if (RealSrcReg)
1646 SavedLI = li_->dupInterval(&DstInt);
1648 // Check if it is necessary to propagate "isDead" property.
1649 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg) {
1650 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1651 bool isDead = mopd->isDead();
1653 // We need to be careful about coalescing a source physical register with a
1654 // virtual register. Once the coalescing is done, it cannot be broken and
1655 // these are not spillable! If the destination interval uses are far away,
1656 // think twice about coalescing them!
1657 if (!isDead && (SrcIsPhys || DstIsPhys)) {
1658 // If the copy is in a loop, take care not to coalesce aggressively if the
1659 // src is coming in from outside the loop (or the dst is out of the loop).
1660 // If it's not in a loop, then determine whether to join them base purely
1661 // by the length of the interval.
1662 if (PhysJoinTweak) {
1664 if (!isWinToJoinVRWithSrcPhysReg(CopyMI, CopyMBB, DstInt, SrcInt)) {
1665 mri_->setRegAllocationHint(DstInt.reg, 0, SrcReg);
1667 DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1668 Again = true; // May be possible to coalesce later.
1672 if (!isWinToJoinVRWithDstPhysReg(CopyMI, CopyMBB, DstInt, SrcInt)) {
1673 mri_->setRegAllocationHint(SrcInt.reg, 0, DstReg);
1675 DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1676 Again = true; // May be possible to coalesce later.
1681 // If the virtual register live interval is long but it has low use
1682 // density, do not join them, instead mark the physical register as its
1683 // allocation preference.
1684 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1685 LiveInterval &JoinPInt = SrcIsPhys ? SrcInt : DstInt;
1686 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1687 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1689 // Don't join with physregs that have a ridiculous number of live
1690 // ranges. The data structure performance is really bad when that
1692 if (JoinPInt.ranges.size() > 1000) {
1693 mri_->setRegAllocationHint(JoinVInt.reg, 0, JoinPReg);
1695 DEBUG(dbgs() << "\tPhysical register too complicated, abort!\n");
1699 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1700 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1701 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1702 float Ratio = 1.0 / Threshold;
1703 if (Length > Threshold &&
1704 (((float)std::distance(mri_->use_nodbg_begin(JoinVReg),
1705 mri_->use_nodbg_end()) / Length) < Ratio)) {
1706 mri_->setRegAllocationHint(JoinVInt.reg, 0, JoinPReg);
1708 DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1709 Again = true; // May be possible to coalesce later.
1716 // Okay, attempt to join these two intervals. On failure, this returns false.
1717 // Otherwise, if one of the intervals being joined is a physreg, this method
1718 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1719 // been modified, so we can use this information below to update aliases.
1720 bool Swapped = false;
1721 // If SrcInt is implicitly defined, it's safe to coalesce.
1722 bool isEmpty = SrcInt.empty();
1723 if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
1724 // Only coalesce an empty interval (defined by implicit_def) with
1725 // another interval which has a valno defined by the CopyMI and the CopyMI
1726 // is a kill of the implicit def.
1727 DEBUG(dbgs() << "Not profitable!\n");
1731 if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
1732 // Coalescing failed.
1734 // If definition of source is defined by trivial computation, try
1735 // rematerializing it.
1736 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
1737 ReMaterializeTrivialDef(SrcInt, DstReg, DstSubIdx, CopyMI))
1740 // If we can eliminate the copy without merging the live ranges, do so now.
1741 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
1742 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1743 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
1744 JoinedCopies.insert(CopyMI);
1745 DEBUG(dbgs() << "Trivial!\n");
1749 // Otherwise, we are unable to join the intervals.
1750 DEBUG(dbgs() << "Interference!\n");
1751 Again = true; // May be possible to coalesce later.
1755 LiveInterval *ResSrcInt = &SrcInt;
1756 LiveInterval *ResDstInt = &DstInt;
1758 std::swap(SrcReg, DstReg);
1759 std::swap(ResSrcInt, ResDstInt);
1761 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1762 "LiveInterval::join didn't work right!");
1764 // If we're about to merge live ranges into a physical register live interval,
1765 // we have to update any aliased register's live ranges to indicate that they
1766 // have clobbered values for this range.
1767 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1768 // If this is a extract_subreg where dst is a physical register, e.g.
1769 // cl = EXTRACT_SUBREG reg1024, 1
1770 // then create and update the actual physical register allocated to RHS.
1771 if (RealDstReg || RealSrcReg) {
1772 LiveInterval &RealInt =
1773 li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
1774 for (LiveInterval::const_vni_iterator I = SavedLI->vni_begin(),
1775 E = SavedLI->vni_end(); I != E; ++I) {
1776 const VNInfo *ValNo = *I;
1777 VNInfo *NewValNo = RealInt.getNextValue(ValNo->def, ValNo->getCopy(),
1778 false, // updated at *
1779 li_->getVNInfoAllocator());
1780 NewValNo->setFlags(ValNo->getFlags()); // * updated here.
1781 RealInt.addKills(NewValNo, ValNo->kills);
1782 RealInt.MergeValueInAsValue(*SavedLI, ValNo, NewValNo);
1784 RealInt.weight += SavedLI->weight;
1785 DstReg = RealDstReg ? RealDstReg : RealSrcReg;
1788 // Update the liveintervals of sub-registers.
1789 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
1790 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*li_, *ResSrcInt,
1791 li_->getVNInfoAllocator());
1794 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1795 // larger super-register.
1796 if ((isExtSubReg || isInsSubReg || isSubRegToReg) &&
1797 !SrcIsPhys && !DstIsPhys) {
1798 if ((isExtSubReg && !Swapped) ||
1799 ((isInsSubReg || isSubRegToReg) && Swapped)) {
1800 ResSrcInt->Copy(*ResDstInt, mri_, li_->getVNInfoAllocator());
1801 std::swap(SrcReg, DstReg);
1802 std::swap(ResSrcInt, ResDstInt);
1806 // Coalescing to a virtual register that is of a sub-register class of the
1807 // other. Make sure the resulting register is set to the right register class.
1811 // This may happen even if it's cross-rc coalescing. e.g.
1812 // %reg1026<def> = SUBREG_TO_REG 0, %reg1037<kill>, 4
1813 // reg1026 -> GR64, reg1037 -> GR32_ABCD. The resulting register will have to
1814 // be allocate a register from GR64_ABCD.
1816 mri_->setRegClass(DstReg, NewRC);
1818 // Remember to delete the copy instruction.
1819 JoinedCopies.insert(CopyMI);
1821 // Some live range has been lengthened due to colaescing, eliminate the
1822 // unnecessary kills.
1823 RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1824 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1825 RemoveUnnecessaryKills(DstReg, *ResDstInt);
1827 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1829 // If we have extended the live range of a physical register, make sure we
1830 // update live-in lists as well.
1831 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1832 const LiveInterval &VRegInterval = li_->getInterval(SrcReg);
1833 SmallVector<MachineBasicBlock*, 16> BlockSeq;
1834 for (LiveInterval::const_iterator I = VRegInterval.begin(),
1835 E = VRegInterval.end(); I != E; ++I ) {
1836 li_->findLiveInMBBs(I->start, I->end, BlockSeq);
1837 for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1838 MachineBasicBlock &block = *BlockSeq[idx];
1839 if (!block.isLiveIn(DstReg))
1840 block.addLiveIn(DstReg);
1846 // SrcReg is guarateed to be the register whose live interval that is
1848 li_->removeInterval(SrcReg);
1850 // Update regalloc hint.
1851 tri_->UpdateRegAllocHint(SrcReg, DstReg, *mf_);
1853 // Manually deleted the live interval copy.
1859 // If resulting interval has a preference that no longer fits because of subreg
1860 // coalescing, just clear the preference.
1861 unsigned Preference = getRegAllocPreference(ResDstInt->reg, *mf_, mri_, tri_);
1862 if (Preference && (isExtSubReg || isInsSubReg || isSubRegToReg) &&
1863 TargetRegisterInfo::isVirtualRegister(ResDstInt->reg)) {
1864 const TargetRegisterClass *RC = mri_->getRegClass(ResDstInt->reg);
1865 if (!RC->contains(Preference))
1866 mri_->setRegAllocationHint(ResDstInt->reg, 0, 0);
1870 dbgs() << "\n\t\tJoined. Result = ";
1871 ResDstInt->print(dbgs(), tri_);
1879 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1880 /// compute what the resultant value numbers for each value in the input two
1881 /// ranges will be. This is complicated by copies between the two which can
1882 /// and will commonly cause multiple value numbers to be merged into one.
1884 /// VN is the value number that we're trying to resolve. InstDefiningValue
1885 /// keeps track of the new InstDefiningValue assignment for the result
1886 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1887 /// whether a value in this or other is a copy from the opposite set.
1888 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1889 /// already been assigned.
1891 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1892 /// contains the value number the copy is from.
1894 static unsigned ComputeUltimateVN(VNInfo *VNI,
1895 SmallVector<VNInfo*, 16> &NewVNInfo,
1896 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1897 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1898 SmallVector<int, 16> &ThisValNoAssignments,
1899 SmallVector<int, 16> &OtherValNoAssignments) {
1900 unsigned VN = VNI->id;
1902 // If the VN has already been computed, just return it.
1903 if (ThisValNoAssignments[VN] >= 0)
1904 return ThisValNoAssignments[VN];
1905 assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1907 // If this val is not a copy from the other val, then it must be a new value
1908 // number in the destination.
1909 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1910 if (I == ThisFromOther.end()) {
1911 NewVNInfo.push_back(VNI);
1912 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1914 VNInfo *OtherValNo = I->second;
1916 // Otherwise, this *is* a copy from the RHS. If the other side has already
1917 // been computed, return it.
1918 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1919 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1921 // Mark this value number as currently being computed, then ask what the
1922 // ultimate value # of the other value is.
1923 ThisValNoAssignments[VN] = -2;
1924 unsigned UltimateVN =
1925 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1926 OtherValNoAssignments, ThisValNoAssignments);
1927 return ThisValNoAssignments[VN] = UltimateVN;
1930 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
1931 return std::find(V.begin(), V.end(), Val) != V.end();
1934 static bool isValNoDefMove(const MachineInstr *MI, unsigned DR, unsigned SR,
1935 const TargetInstrInfo *TII,
1936 const TargetRegisterInfo *TRI) {
1937 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1938 if (TII->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
1940 else if (MI->isExtractSubreg()) {
1941 DstReg = MI->getOperand(0).getReg();
1942 SrcReg = MI->getOperand(1).getReg();
1943 } else if (MI->isSubregToReg() ||
1944 MI->isInsertSubreg()) {
1945 DstReg = MI->getOperand(0).getReg();
1946 SrcReg = MI->getOperand(2).getReg();
1949 return (SrcReg == SR || TRI->isSuperRegister(SR, SrcReg)) &&
1950 (DstReg == DR || TRI->isSuperRegister(DR, DstReg));
1953 /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1954 /// the specified live interval is defined by a copy from the specified
1956 bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1959 unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1962 // FIXME: Do isPHIDef and isDefAccurate both need to be tested?
1963 if ((LR->valno->isPHIDef() || !LR->valno->isDefAccurate()) &&
1964 TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1965 *tri_->getSuperRegisters(li.reg)) {
1966 // It's a sub-register live interval, we may not have precise information.
1968 MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1969 if (DefMI && isValNoDefMove(DefMI, li.reg, Reg, tii_, tri_)) {
1970 // Cache computed info.
1971 LR->valno->def = LR->start;
1972 LR->valno->setCopy(DefMI);
1980 /// ValueLiveAt - Return true if the LiveRange pointed to by the given
1981 /// iterator, or any subsequent range with the same value number,
1982 /// is live at the given point.
1983 bool SimpleRegisterCoalescing::ValueLiveAt(LiveInterval::iterator LRItr,
1984 LiveInterval::iterator LREnd,
1985 SlotIndex defPoint) const {
1986 for (const VNInfo *valno = LRItr->valno;
1987 (LRItr != LREnd) && (LRItr->valno == valno); ++LRItr) {
1988 if (LRItr->contains(defPoint))
1996 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1997 /// caller of this method must guarantee that the RHS only contains a single
1998 /// value number and that the RHS is not defined by a copy from this
1999 /// interval. This returns false if the intervals are not joinable, or it
2000 /// joins them and returns true.
2001 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
2002 assert(RHS.containsOneValue());
2004 // Some number (potentially more than one) value numbers in the current
2005 // interval may be defined as copies from the RHS. Scan the overlapping
2006 // portions of the LHS and RHS, keeping track of this and looking for
2007 // overlapping live ranges that are NOT defined as copies. If these exist, we
2010 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
2011 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
2013 if (LHSIt->start < RHSIt->start) {
2014 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
2015 if (LHSIt != LHS.begin()) --LHSIt;
2016 } else if (RHSIt->start < LHSIt->start) {
2017 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
2018 if (RHSIt != RHS.begin()) --RHSIt;
2021 SmallVector<VNInfo*, 8> EliminatedLHSVals;
2024 // Determine if these live intervals overlap.
2025 bool Overlaps = false;
2026 if (LHSIt->start <= RHSIt->start)
2027 Overlaps = LHSIt->end > RHSIt->start;
2029 Overlaps = RHSIt->end > LHSIt->start;
2031 // If the live intervals overlap, there are two interesting cases: if the
2032 // LHS interval is defined by a copy from the RHS, it's ok and we record
2033 // that the LHS value # is the same as the RHS. If it's not, then we cannot
2034 // coalesce these live ranges and we bail out.
2036 // If we haven't already recorded that this value # is safe, check it.
2037 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
2038 // If it's re-defined by an early clobber somewhere in the live range,
2039 // then conservatively abort coalescing.
2040 if (LHSIt->valno->hasRedefByEC())
2042 // Copy from the RHS?
2043 if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
2044 return false; // Nope, bail out.
2046 if (ValueLiveAt(LHSIt, LHS.end(), RHSIt->valno->def))
2047 // Here is an interesting situation:
2049 // vr1025 = copy vr1024
2054 // Even though vr1025 is copied from vr1024, it's not safe to
2055 // coalesce them since the live range of vr1025 intersects the
2056 // def of vr1024. This happens because vr1025 is assigned the
2057 // value of the previous iteration of vr1024.
2059 EliminatedLHSVals.push_back(LHSIt->valno);
2062 // We know this entire LHS live range is okay, so skip it now.
2063 if (++LHSIt == LHSEnd) break;
2067 if (LHSIt->end < RHSIt->end) {
2068 if (++LHSIt == LHSEnd) break;
2070 // One interesting case to check here. It's possible that we have
2071 // something like "X3 = Y" which defines a new value number in the LHS,
2072 // and is the last use of this liverange of the RHS. In this case, we
2073 // want to notice this copy (so that it gets coalesced away) even though
2074 // the live ranges don't actually overlap.
2075 if (LHSIt->start == RHSIt->end) {
2076 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
2077 // We already know that this value number is going to be merged in
2078 // if coalescing succeeds. Just skip the liverange.
2079 if (++LHSIt == LHSEnd) break;
2081 // If it's re-defined by an early clobber somewhere in the live range,
2082 // then conservatively abort coalescing.
2083 if (LHSIt->valno->hasRedefByEC())
2085 // Otherwise, if this is a copy from the RHS, mark it as being merged
2087 if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
2088 if (ValueLiveAt(LHSIt, LHS.end(), RHSIt->valno->def))
2089 // Here is an interesting situation:
2091 // vr1025 = copy vr1024
2096 // Even though vr1025 is copied from vr1024, it's not safe to
2097 // coalesced them since live range of vr1025 intersects the
2098 // def of vr1024. This happens because vr1025 is assigned the
2099 // value of the previous iteration of vr1024.
2101 EliminatedLHSVals.push_back(LHSIt->valno);
2103 // We know this entire LHS live range is okay, so skip it now.
2104 if (++LHSIt == LHSEnd) break;
2109 if (++RHSIt == RHSEnd) break;
2113 // If we got here, we know that the coalescing will be successful and that
2114 // the value numbers in EliminatedLHSVals will all be merged together. Since
2115 // the most common case is that EliminatedLHSVals has a single number, we
2116 // optimize for it: if there is more than one value, we merge them all into
2117 // the lowest numbered one, then handle the interval as if we were merging
2118 // with one value number.
2119 VNInfo *LHSValNo = NULL;
2120 if (EliminatedLHSVals.size() > 1) {
2121 // Loop through all the equal value numbers merging them into the smallest
2123 VNInfo *Smallest = EliminatedLHSVals[0];
2124 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
2125 if (EliminatedLHSVals[i]->id < Smallest->id) {
2126 // Merge the current notion of the smallest into the smaller one.
2127 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
2128 Smallest = EliminatedLHSVals[i];
2130 // Merge into the smallest.
2131 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
2134 LHSValNo = Smallest;
2135 } else if (EliminatedLHSVals.empty()) {
2136 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
2137 *tri_->getSuperRegisters(LHS.reg))
2138 // Imprecise sub-register information. Can't handle it.
2140 llvm_unreachable("No copies from the RHS?");
2142 LHSValNo = EliminatedLHSVals[0];
2145 // Okay, now that there is a single LHS value number that we're merging the
2146 // RHS into, update the value number info for the LHS to indicate that the
2147 // value number is defined where the RHS value number was.
2148 const VNInfo *VNI = RHS.getValNumInfo(0);
2149 LHSValNo->def = VNI->def;
2150 LHSValNo->setCopy(VNI->getCopy());
2152 // Okay, the final step is to loop over the RHS live intervals, adding them to
2154 if (VNI->hasPHIKill())
2155 LHSValNo->setHasPHIKill(true);
2156 LHS.addKills(LHSValNo, VNI->kills);
2157 LHS.MergeRangesInAsValue(RHS, LHSValNo);
2159 LHS.ComputeJoinedWeight(RHS);
2161 // Update regalloc hint if both are virtual registers.
2162 if (TargetRegisterInfo::isVirtualRegister(LHS.reg) &&
2163 TargetRegisterInfo::isVirtualRegister(RHS.reg)) {
2164 std::pair<unsigned, unsigned> RHSPref = mri_->getRegAllocationHint(RHS.reg);
2165 std::pair<unsigned, unsigned> LHSPref = mri_->getRegAllocationHint(LHS.reg);
2166 if (RHSPref != LHSPref)
2167 mri_->setRegAllocationHint(LHS.reg, RHSPref.first, RHSPref.second);
2170 // Update the liveintervals of sub-registers.
2171 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg))
2172 for (const unsigned *AS = tri_->getSubRegisters(LHS.reg); *AS; ++AS)
2173 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*li_, LHS,
2174 li_->getVNInfoAllocator());
2179 /// JoinIntervals - Attempt to join these two intervals. On failure, this
2180 /// returns false. Otherwise, if one of the intervals being joined is a
2181 /// physreg, this method always canonicalizes LHS to be it. The output
2182 /// "RHS" will not have been modified, so we can use this information
2183 /// below to update aliases.
2185 SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS,
2187 // Compute the final value assignment, assuming that the live ranges can be
2189 SmallVector<int, 16> LHSValNoAssignments;
2190 SmallVector<int, 16> RHSValNoAssignments;
2191 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
2192 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
2193 SmallVector<VNInfo*, 16> NewVNInfo;
2195 // If a live interval is a physical register, conservatively check if any
2196 // of its sub-registers is overlapping the live interval of the virtual
2197 // register. If so, do not coalesce.
2198 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
2199 *tri_->getSubRegisters(LHS.reg)) {
2200 // If it's coalescing a virtual register to a physical register, estimate
2201 // its live interval length. This is the *cost* of scanning an entire live
2202 // interval. If the cost is low, we'll do an exhaustive check instead.
2204 // If this is something like this:
2212 // That is, the live interval of v1024 crosses a bb. Then we can't rely on
2213 // less conservative check. It's possible a sub-register is defined before
2214 // v1024 (or live in) and live out of BB1.
2215 if (RHS.containsOneValue() &&
2216 li_->intervalIsInOneMBB(RHS) &&
2217 li_->getApproximateInstructionCount(RHS) <= 10) {
2218 // Perform a more exhaustive check for some common cases.
2219 if (li_->conflictsWithSubPhysRegRef(RHS, LHS.reg, true, JoinedCopies))
2222 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
2223 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
2225 dbgs() << "Interfere with sub-register ";
2226 li_->getInterval(*SR).print(dbgs(), tri_);
2231 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
2232 *tri_->getSubRegisters(RHS.reg)) {
2233 if (LHS.containsOneValue() &&
2234 li_->getApproximateInstructionCount(LHS) <= 10) {
2235 // Perform a more exhaustive check for some common cases.
2236 if (li_->conflictsWithSubPhysRegRef(LHS, RHS.reg, false, JoinedCopies))
2239 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
2240 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
2242 dbgs() << "Interfere with sub-register ";
2243 li_->getInterval(*SR).print(dbgs(), tri_);
2250 // Compute ultimate value numbers for the LHS and RHS values.
2251 if (RHS.containsOneValue()) {
2252 // Copies from a liveinterval with a single value are simple to handle and
2253 // very common, handle the special case here. This is important, because
2254 // often RHS is small and LHS is large (e.g. a physreg).
2256 // Find out if the RHS is defined as a copy from some value in the LHS.
2257 int RHSVal0DefinedFromLHS = -1;
2259 VNInfo *RHSValNoInfo = NULL;
2260 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
2261 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
2262 if (RHSSrcReg == 0 || RHSSrcReg != LHS.reg) {
2263 // If RHS is not defined as a copy from the LHS, we can use simpler and
2264 // faster checks to see if the live ranges are coalescable. This joiner
2265 // can't swap the LHS/RHS intervals though.
2266 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2267 return SimpleJoin(LHS, RHS);
2269 RHSValNoInfo = RHSValNoInfo0;
2272 // It was defined as a copy from the LHS, find out what value # it is.
2274 LHS.getLiveRangeContaining(RHSValNoInfo0->def.getPrevSlot())->valno;
2275 RHSValID = RHSValNoInfo->id;
2276 RHSVal0DefinedFromLHS = RHSValID;
2279 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2280 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2281 NewVNInfo.resize(LHS.getNumValNums(), NULL);
2283 // Okay, *all* of the values in LHS that are defined as a copy from RHS
2284 // should now get updated.
2285 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2288 unsigned VN = VNI->id;
2289 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
2290 if (LHSSrcReg != RHS.reg) {
2291 // If this is not a copy from the RHS, its value number will be
2292 // unmodified by the coalescing.
2293 NewVNInfo[VN] = VNI;
2294 LHSValNoAssignments[VN] = VN;
2295 } else if (RHSValID == -1) {
2296 // Otherwise, it is a copy from the RHS, and we don't already have a
2297 // value# for it. Keep the current value number, but remember it.
2298 LHSValNoAssignments[VN] = RHSValID = VN;
2299 NewVNInfo[VN] = RHSValNoInfo;
2300 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
2302 // Otherwise, use the specified value #.
2303 LHSValNoAssignments[VN] = RHSValID;
2304 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
2305 NewVNInfo[VN] = RHSValNoInfo;
2306 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
2310 NewVNInfo[VN] = VNI;
2311 LHSValNoAssignments[VN] = VN;
2315 assert(RHSValID != -1 && "Didn't find value #?");
2316 RHSValNoAssignments[0] = RHSValID;
2317 if (RHSVal0DefinedFromLHS != -1) {
2318 // This path doesn't go through ComputeUltimateVN so just set
2320 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
2323 // Loop over the value numbers of the LHS, seeing if any are defined from
2325 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2328 if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy?
2331 // DstReg is known to be a register in the LHS interval. If the src is
2332 // from the RHS interval, we can use its value #.
2333 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
2336 // Figure out the value # from the RHS.
2337 LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
2338 assert(lr && "Cannot find live range");
2339 LHSValsDefinedFromRHS[VNI] = lr->valno;
2342 // Loop over the value numbers of the RHS, seeing if any are defined from
2344 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2347 if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy?
2350 // DstReg is known to be a register in the RHS interval. If the src is
2351 // from the LHS interval, we can use its value #.
2352 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
2355 // Figure out the value # from the LHS.
2356 LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
2357 assert(lr && "Cannot find live range");
2358 RHSValsDefinedFromLHS[VNI] = lr->valno;
2361 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2362 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2363 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
2365 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2368 unsigned VN = VNI->id;
2369 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
2371 ComputeUltimateVN(VNI, NewVNInfo,
2372 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
2373 LHSValNoAssignments, RHSValNoAssignments);
2375 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2378 unsigned VN = VNI->id;
2379 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
2381 // If this value number isn't a copy from the LHS, it's a new number.
2382 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
2383 NewVNInfo.push_back(VNI);
2384 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
2388 ComputeUltimateVN(VNI, NewVNInfo,
2389 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
2390 RHSValNoAssignments, LHSValNoAssignments);
2394 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
2395 // interval lists to see if these intervals are coalescable.
2396 LiveInterval::const_iterator I = LHS.begin();
2397 LiveInterval::const_iterator IE = LHS.end();
2398 LiveInterval::const_iterator J = RHS.begin();
2399 LiveInterval::const_iterator JE = RHS.end();
2401 // Skip ahead until the first place of potential sharing.
2402 if (I->start < J->start) {
2403 I = std::upper_bound(I, IE, J->start);
2404 if (I != LHS.begin()) --I;
2405 } else if (J->start < I->start) {
2406 J = std::upper_bound(J, JE, I->start);
2407 if (J != RHS.begin()) --J;
2411 // Determine if these two live ranges overlap.
2413 if (I->start < J->start) {
2414 Overlaps = I->end > J->start;
2416 Overlaps = J->end > I->start;
2419 // If so, check value # info to determine if they are really different.
2421 // If the live range overlap will map to the same value number in the
2422 // result liverange, we can still coalesce them. If not, we can't.
2423 if (LHSValNoAssignments[I->valno->id] !=
2424 RHSValNoAssignments[J->valno->id])
2426 // If it's re-defined by an early clobber somewhere in the live range,
2427 // then conservatively abort coalescing.
2428 if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
2432 if (I->end < J->end) {
2441 // Update kill info. Some live ranges are extended due to copy coalescing.
2442 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
2443 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
2444 VNInfo *VNI = I->first;
2445 unsigned LHSValID = LHSValNoAssignments[VNI->id];
2446 NewVNInfo[LHSValID]->removeKill(VNI->def);
2447 if (VNI->hasPHIKill())
2448 NewVNInfo[LHSValID]->setHasPHIKill(true);
2449 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
2452 // Update kill info. Some live ranges are extended due to copy coalescing.
2453 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
2454 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
2455 VNInfo *VNI = I->first;
2456 unsigned RHSValID = RHSValNoAssignments[VNI->id];
2457 NewVNInfo[RHSValID]->removeKill(VNI->def);
2458 if (VNI->hasPHIKill())
2459 NewVNInfo[RHSValID]->setHasPHIKill(true);
2460 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
2463 // If we get here, we know that we can coalesce the live ranges. Ask the
2464 // intervals to coalesce themselves now.
2465 if ((RHS.ranges.size() > LHS.ranges.size() &&
2466 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
2467 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2468 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo,
2472 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
2480 // DepthMBBCompare - Comparison predicate that sort first based on the loop
2481 // depth of the basic block (the unsigned), and then on the MBB number.
2482 struct DepthMBBCompare {
2483 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
2484 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
2485 // Deeper loops first
2486 if (LHS.first != RHS.first)
2487 return LHS.first > RHS.first;
2489 // Prefer blocks that are more connected in the CFG. This takes care of
2490 // the most difficult copies first while intervals are short.
2491 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
2492 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
2496 // As a last resort, sort by block number.
2497 return LHS.second->getNumber() < RHS.second->getNumber();
2502 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
2503 std::vector<CopyRec> &TryAgain) {
2504 DEBUG(dbgs() << MBB->getName() << ":\n");
2506 std::vector<CopyRec> VirtCopies;
2507 std::vector<CopyRec> PhysCopies;
2508 std::vector<CopyRec> ImpDefCopies;
2509 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2511 MachineInstr *Inst = MII++;
2513 // If this isn't a copy nor a extract_subreg, we can't join intervals.
2514 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2515 bool isInsUndef = false;
2516 if (Inst->isExtractSubreg()) {
2517 DstReg = Inst->getOperand(0).getReg();
2518 SrcReg = Inst->getOperand(1).getReg();
2519 } else if (Inst->isInsertSubreg()) {
2520 DstReg = Inst->getOperand(0).getReg();
2521 SrcReg = Inst->getOperand(2).getReg();
2522 if (Inst->getOperand(1).isUndef())
2524 } else if (Inst->isInsertSubreg() || Inst->isSubregToReg()) {
2525 DstReg = Inst->getOperand(0).getReg();
2526 SrcReg = Inst->getOperand(2).getReg();
2527 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
2530 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
2531 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
2533 (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty()))
2534 ImpDefCopies.push_back(CopyRec(Inst, 0));
2535 else if (SrcIsPhys || DstIsPhys)
2536 PhysCopies.push_back(CopyRec(Inst, 0));
2538 VirtCopies.push_back(CopyRec(Inst, 0));
2541 // Try coalescing implicit copies and insert_subreg <undef> first,
2542 // followed by copies to / from physical registers, then finally copies
2543 // from virtual registers to virtual registers.
2544 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
2545 CopyRec &TheCopy = ImpDefCopies[i];
2547 if (!JoinCopy(TheCopy, Again))
2549 TryAgain.push_back(TheCopy);
2551 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
2552 CopyRec &TheCopy = PhysCopies[i];
2554 if (!JoinCopy(TheCopy, Again))
2556 TryAgain.push_back(TheCopy);
2558 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
2559 CopyRec &TheCopy = VirtCopies[i];
2561 if (!JoinCopy(TheCopy, Again))
2563 TryAgain.push_back(TheCopy);
2567 void SimpleRegisterCoalescing::joinIntervals() {
2568 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
2570 std::vector<CopyRec> TryAgainList;
2571 if (loopInfo->empty()) {
2572 // If there are no loops in the function, join intervals in function order.
2573 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
2575 CopyCoalesceInMBB(I, TryAgainList);
2577 // Otherwise, join intervals in inner loops before other intervals.
2578 // Unfortunately we can't just iterate over loop hierarchy here because
2579 // there may be more MBB's than BB's. Collect MBB's for sorting.
2581 // Join intervals in the function prolog first. We want to join physical
2582 // registers with virtual registers before the intervals got too long.
2583 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
2584 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
2585 MachineBasicBlock *MBB = I;
2586 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
2589 // Sort by loop depth.
2590 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2592 // Finally, join intervals in loop nest order.
2593 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2594 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
2597 // Joining intervals can allow other intervals to be joined. Iteratively join
2598 // until we make no progress.
2599 bool ProgressMade = true;
2600 while (ProgressMade) {
2601 ProgressMade = false;
2603 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
2604 CopyRec &TheCopy = TryAgainList[i];
2609 bool Success = JoinCopy(TheCopy, Again);
2610 if (Success || !Again) {
2611 TheCopy.MI = 0; // Mark this one as done.
2612 ProgressMade = true;
2618 /// Return true if the two specified registers belong to different register
2619 /// classes. The registers may be either phys or virt regs.
2621 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
2622 unsigned RegB) const {
2623 // Get the register classes for the first reg.
2624 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
2625 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
2626 "Shouldn't consider two physregs!");
2627 return !mri_->getRegClass(RegB)->contains(RegA);
2630 // Compare against the regclass for the second reg.
2631 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
2632 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
2633 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
2634 return RegClassA != RegClassB;
2636 return !RegClassA->contains(RegB);
2639 /// lastRegisterUse - Returns the last (non-debug) use of the specific register
2640 /// between cycles Start and End or NULL if there are no uses.
2642 SimpleRegisterCoalescing::lastRegisterUse(SlotIndex Start,
2645 SlotIndex &UseIdx) const{
2646 UseIdx = SlotIndex();
2647 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2648 MachineOperand *LastUse = NULL;
2649 for (MachineRegisterInfo::use_nodbg_iterator I = mri_->use_nodbg_begin(Reg),
2650 E = mri_->use_nodbg_end(); I != E; ++I) {
2651 MachineOperand &Use = I.getOperand();
2652 MachineInstr *UseMI = Use.getParent();
2653 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2654 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2656 // Ignore identity copies.
2658 SlotIndex Idx = li_->getInstructionIndex(UseMI);
2659 // FIXME: Should this be Idx != UseIdx? SlotIndex() will return something
2660 // that compares higher than any other interval.
2661 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
2663 UseIdx = Idx.getUseIndex();
2669 SlotIndex s = Start;
2670 SlotIndex e = End.getPrevSlot().getBaseIndex();
2672 // Skip deleted instructions
2673 MachineInstr *MI = li_->getInstructionFromIndex(e);
2674 while (e != SlotIndex() && e.getPrevIndex() >= s && !MI) {
2675 e = e.getPrevIndex();
2676 MI = li_->getInstructionFromIndex(e);
2678 if (e < s || MI == NULL)
2681 // Ignore identity copies.
2682 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2683 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2685 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2686 MachineOperand &Use = MI->getOperand(i);
2687 if (Use.isReg() && Use.isUse() && Use.getReg() &&
2688 tri_->regsOverlap(Use.getReg(), Reg)) {
2689 UseIdx = e.getUseIndex();
2694 e = e.getPrevIndex();
2700 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
2701 if (TargetRegisterInfo::isPhysicalRegister(reg))
2702 dbgs() << tri_->getName(reg);
2704 dbgs() << "%reg" << reg;
2707 void SimpleRegisterCoalescing::releaseMemory() {
2708 JoinedCopies.clear();
2709 ReMatCopies.clear();
2713 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2715 mri_ = &fn.getRegInfo();
2716 tm_ = &fn.getTarget();
2717 tri_ = tm_->getRegisterInfo();
2718 tii_ = tm_->getInstrInfo();
2719 li_ = &getAnalysis<LiveIntervals>();
2720 AA = &getAnalysis<AliasAnalysis>();
2721 loopInfo = &getAnalysis<MachineLoopInfo>();
2723 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
2724 << "********** Function: "
2725 << ((Value*)mf_->getFunction())->getName() << '\n');
2727 allocatableRegs_ = tri_->getAllocatableSet(fn);
2728 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2729 E = tri_->regclass_end(); I != E; ++I)
2730 allocatableRCRegs_.insert(std::make_pair(*I,
2731 tri_->getAllocatableSet(fn, *I)));
2733 // Join (coalesce) intervals if requested.
2734 if (EnableJoining) {
2737 dbgs() << "********** INTERVALS POST JOINING **********\n";
2738 for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
2740 I->second->print(dbgs(), tri_);
2746 // Perform a final pass over the instructions and compute spill weights
2747 // and remove identity moves.
2748 SmallVector<unsigned, 4> DeadDefs;
2749 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2750 mbbi != mbbe; ++mbbi) {
2751 MachineBasicBlock* mbb = mbbi;
2752 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2754 MachineInstr *MI = mii;
2755 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2756 if (JoinedCopies.count(MI)) {
2757 // Delete all coalesced copies.
2758 bool DoDelete = true;
2759 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
2760 assert((MI->isExtractSubreg() || MI->isInsertSubreg() ||
2761 MI->isSubregToReg()) && "Unrecognized copy instruction");
2762 DstReg = MI->getOperand(0).getReg();
2763 if (TargetRegisterInfo::isPhysicalRegister(DstReg))
2764 // Do not delete extract_subreg, insert_subreg of physical
2765 // registers unless the definition is dead. e.g.
2766 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
2767 // or else the scavenger may complain. LowerSubregs will
2768 // delete them later.
2771 if (MI->registerDefIsDead(DstReg)) {
2772 LiveInterval &li = li_->getInterval(DstReg);
2773 if (!ShortenDeadCopySrcLiveRange(li, MI))
2774 ShortenDeadCopyLiveRange(li, MI);
2778 mii = llvm::next(mii);
2780 li_->RemoveMachineInstrFromMaps(MI);
2781 mii = mbbi->erase(mii);
2787 // Now check if this is a remat'ed def instruction which is now dead.
2788 if (ReMatDefs.count(MI)) {
2790 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2791 const MachineOperand &MO = MI->getOperand(i);
2794 unsigned Reg = MO.getReg();
2797 if (TargetRegisterInfo::isVirtualRegister(Reg))
2798 DeadDefs.push_back(Reg);
2801 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
2802 !mri_->use_empty(Reg)) {
2808 while (!DeadDefs.empty()) {
2809 unsigned DeadDef = DeadDefs.back();
2810 DeadDefs.pop_back();
2811 RemoveDeadDef(li_->getInterval(DeadDef), MI);
2813 li_->RemoveMachineInstrFromMaps(mii);
2814 mii = mbbi->erase(mii);
2820 // If the move will be an identity move delete it
2821 bool isMove= tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
2822 if (isMove && SrcReg == DstReg) {
2823 if (li_->hasInterval(SrcReg)) {
2824 LiveInterval &RegInt = li_->getInterval(SrcReg);
2825 // If def of this move instruction is dead, remove its live range
2826 // from the dstination register's live interval.
2827 if (MI->registerDefIsDead(DstReg)) {
2828 if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
2829 ShortenDeadCopyLiveRange(RegInt, MI);
2832 li_->RemoveMachineInstrFromMaps(MI);
2833 mii = mbbi->erase(mii);
2845 /// print - Implement the dump method.
2846 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
2850 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2851 return new SimpleRegisterCoalescing();
2854 // Make sure that anything that uses RegisterCoalescer pulls in this file...
2855 DEFINING_FILE_FOR(SimpleRegisterCoalescing)