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/OwningPtr.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/STLExtras.h"
42 STATISTIC(numJoins
, "Number of interval joins performed");
43 STATISTIC(numCrossRCs
, "Number of cross class joins performed");
44 STATISTIC(numCommutes
, "Number of instruction commuting performed");
45 STATISTIC(numExtends
, "Number of copies extended");
46 STATISTIC(NumReMats
, "Number of instructions re-materialized");
47 STATISTIC(numPeep
, "Number of identity moves eliminated after coalescing");
48 STATISTIC(numAborts
, "Number of times interval joining aborted");
49 STATISTIC(numDeadValNo
, "Number of valno def marked dead");
51 char SimpleRegisterCoalescing::ID
= 0;
53 EnableJoining("join-liveintervals",
54 cl::desc("Coalesce copies (default=true)"),
58 DisableCrossClassJoin("disable-cross-class-join",
59 cl::desc("Avoid coalescing cross register class copies"),
60 cl::init(false), cl::Hidden
);
63 DisablePhysicalJoin("disable-physical-join",
64 cl::desc("Avoid coalescing physical register copies"),
65 cl::init(false), cl::Hidden
);
67 INITIALIZE_AG_PASS_BEGIN(SimpleRegisterCoalescing
, RegisterCoalescer
,
68 "simple-register-coalescing", "Simple Register Coalescing",
70 INITIALIZE_PASS_DEPENDENCY(LiveIntervals
)
71 INITIALIZE_PASS_DEPENDENCY(SlotIndexes
)
72 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo
)
73 INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination
)
74 INITIALIZE_PASS_DEPENDENCY(PHIElimination
)
75 INITIALIZE_PASS_DEPENDENCY(TwoAddressInstructionPass
)
76 INITIALIZE_AG_DEPENDENCY(AliasAnalysis
)
77 INITIALIZE_AG_PASS_END(SimpleRegisterCoalescing
, RegisterCoalescer
,
78 "simple-register-coalescing", "Simple Register Coalescing",
81 char &llvm::SimpleRegisterCoalescingID
= SimpleRegisterCoalescing::ID
;
83 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage
&AU
) const {
85 AU
.addRequired
<AliasAnalysis
>();
86 AU
.addRequired
<LiveIntervals
>();
87 AU
.addPreserved
<LiveIntervals
>();
88 AU
.addPreserved
<SlotIndexes
>();
89 AU
.addRequired
<MachineLoopInfo
>();
90 AU
.addPreserved
<MachineLoopInfo
>();
91 AU
.addPreservedID(MachineDominatorsID
);
93 AU
.addPreservedID(StrongPHIEliminationID
);
95 AU
.addPreservedID(PHIEliminationID
);
96 AU
.addPreservedID(TwoAddressInstructionPassID
);
97 MachineFunctionPass::getAnalysisUsage(AU
);
100 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
101 /// being the source and IntB being the dest, thus this defines a value number
102 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
103 /// see if we can merge these two pieces of B into a single value number,
104 /// eliminating a copy. For example:
108 /// B1 = A3 <- this copy
110 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
111 /// value number to be replaced with B0 (which simplifies the B liveinterval).
113 /// This returns true if an interval was modified.
115 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(const CoalescerPair
&CP
,
116 MachineInstr
*CopyMI
) {
117 // Bail if there is no dst interval - can happen when merging physical subreg
119 if (!li_
->hasInterval(CP
.getDstReg()))
123 li_
->getInterval(CP
.isFlipped() ? CP
.getDstReg() : CP
.getSrcReg());
125 li_
->getInterval(CP
.isFlipped() ? CP
.getSrcReg() : CP
.getDstReg());
126 SlotIndex CopyIdx
= li_
->getInstructionIndex(CopyMI
).getDefIndex();
128 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
129 // the example above.
130 LiveInterval::iterator BLR
= IntB
.FindLiveRangeContaining(CopyIdx
);
131 if (BLR
== IntB
.end()) return false;
132 VNInfo
*BValNo
= BLR
->valno
;
134 // Get the location that B is defined at. Two options: either this value has
135 // an unknown definition point or it is defined at CopyIdx. If unknown, we
137 if (!BValNo
->isDefByCopy()) return false;
138 assert(BValNo
->def
== CopyIdx
&& "Copy doesn't define the value?");
140 // AValNo is the value number in A that defines the copy, A3 in the example.
141 SlotIndex CopyUseIdx
= CopyIdx
.getUseIndex();
142 LiveInterval::iterator ALR
= IntA
.FindLiveRangeContaining(CopyUseIdx
);
143 // The live range might not exist after fun with physreg coalescing.
144 if (ALR
== IntA
.end()) return false;
145 VNInfo
*AValNo
= ALR
->valno
;
146 // If it's re-defined by an early clobber somewhere in the live range, then
147 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
149 // 172 %ECX<def> = MOV32rr %reg1039<kill>
150 // 180 INLINEASM <es:subl $5,$1
151 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9,
153 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
154 // 188 %EAX<def> = MOV32rr %EAX<kill>
155 // 196 %ECX<def> = MOV32rr %ECX<kill>
156 // 204 %ECX<def> = MOV32rr %ECX<kill>
157 // 212 %EAX<def> = MOV32rr %EAX<kill>
158 // 220 %EAX<def> = MOV32rr %EAX
159 // 228 %reg1039<def> = MOV32rr %ECX<kill>
160 // The early clobber operand ties ECX input to the ECX def.
162 // The live interval of ECX is represented as this:
163 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
164 // The coalescer has no idea there was a def in the middle of [174,230].
165 if (AValNo
->hasRedefByEC())
168 // If AValNo is defined as a copy from IntB, we can potentially process this.
169 // Get the instruction that defines this value number.
170 if (!CP
.isCoalescable(AValNo
->getCopy()))
173 // Get the LiveRange in IntB that this value number starts with.
174 LiveInterval::iterator ValLR
=
175 IntB
.FindLiveRangeContaining(AValNo
->def
.getPrevSlot());
176 if (ValLR
== IntB
.end())
179 // Make sure that the end of the live range is inside the same block as
181 MachineInstr
*ValLREndInst
=
182 li_
->getInstructionFromIndex(ValLR
->end
.getPrevSlot());
183 if (!ValLREndInst
|| ValLREndInst
->getParent() != CopyMI
->getParent())
186 // Okay, we now know that ValLR ends in the same block that the CopyMI
187 // live-range starts. If there are no intervening live ranges between them in
188 // IntB, we can merge them.
189 if (ValLR
+1 != BLR
) return false;
191 // If a live interval is a physical register, conservatively check if any
192 // of its sub-registers is overlapping the live interval of the virtual
193 // register. If so, do not coalesce.
194 if (TargetRegisterInfo::isPhysicalRegister(IntB
.reg
) &&
195 *tri_
->getSubRegisters(IntB
.reg
)) {
196 for (const unsigned* SR
= tri_
->getSubRegisters(IntB
.reg
); *SR
; ++SR
)
197 if (li_
->hasInterval(*SR
) && IntA
.overlaps(li_
->getInterval(*SR
))) {
199 dbgs() << "\t\tInterfere with sub-register ";
200 li_
->getInterval(*SR
).print(dbgs(), tri_
);
207 dbgs() << "Extending: ";
208 IntB
.print(dbgs(), tri_
);
211 SlotIndex FillerStart
= ValLR
->end
, FillerEnd
= BLR
->start
;
212 // We are about to delete CopyMI, so need to remove it as the 'instruction
213 // that defines this value #'. Update the valnum with the new defining
215 BValNo
->def
= FillerStart
;
218 // Okay, we can merge them. We need to insert a new liverange:
219 // [ValLR.end, BLR.begin) of either value number, then we merge the
220 // two value numbers.
221 IntB
.addRange(LiveRange(FillerStart
, FillerEnd
, BValNo
));
223 // If the IntB live range is assigned to a physical register, and if that
224 // physreg has sub-registers, update their live intervals as well.
225 if (TargetRegisterInfo::isPhysicalRegister(IntB
.reg
)) {
226 for (const unsigned *SR
= tri_
->getSubRegisters(IntB
.reg
); *SR
; ++SR
) {
227 if (!li_
->hasInterval(*SR
))
229 LiveInterval
&SRLI
= li_
->getInterval(*SR
);
230 SRLI
.addRange(LiveRange(FillerStart
, FillerEnd
,
231 SRLI
.getNextValue(FillerStart
, 0,
232 li_
->getVNInfoAllocator())));
236 // Okay, merge "B1" into the same value number as "B0".
237 if (BValNo
!= ValLR
->valno
) {
238 IntB
.MergeValueNumberInto(BValNo
, ValLR
->valno
);
241 dbgs() << " result = ";
242 IntB
.print(dbgs(), tri_
);
246 // If the source instruction was killing the source register before the
247 // merge, unset the isKill marker given the live range has been extended.
248 int UIdx
= ValLREndInst
->findRegisterUseOperandIdx(IntB
.reg
, true);
250 ValLREndInst
->getOperand(UIdx
).setIsKill(false);
253 // If the copy instruction was killing the destination register before the
254 // merge, find the last use and trim the live range. That will also add the
256 if (ALR
->end
== CopyIdx
)
257 TrimLiveIntervalToLastUse(CopyUseIdx
, CopyMI
->getParent(), IntA
, ALR
);
263 /// HasOtherReachingDefs - Return true if there are definitions of IntB
264 /// other than BValNo val# that can reach uses of AValno val# of IntA.
265 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval
&IntA
,
269 for (LiveInterval::iterator AI
= IntA
.begin(), AE
= IntA
.end();
271 if (AI
->valno
!= AValNo
) continue;
272 LiveInterval::Ranges::iterator BI
=
273 std::upper_bound(IntB
.ranges
.begin(), IntB
.ranges
.end(), AI
->start
);
274 if (BI
!= IntB
.ranges
.begin())
276 for (; BI
!= IntB
.ranges
.end() && AI
->end
>= BI
->start
; ++BI
) {
277 if (BI
->valno
== BValNo
)
279 if (BI
->start
<= AI
->start
&& BI
->end
> AI
->start
)
281 if (BI
->start
> AI
->start
&& BI
->start
< AI
->end
)
288 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
289 /// IntA being the source and IntB being the dest, thus this defines a value
290 /// number in IntB. If the source value number (in IntA) is defined by a
291 /// commutable instruction and its other operand is coalesced to the copy dest
292 /// register, see if we can transform the copy into a noop by commuting the
293 /// definition. For example,
295 /// A3 = op A2 B0<kill>
297 /// B1 = A3 <- this copy
299 /// = op A3 <- more uses
303 /// B2 = op B0 A2<kill>
305 /// B1 = B2 <- now an identify copy
307 /// = op B2 <- more uses
309 /// This returns true if an interval was modified.
311 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(const CoalescerPair
&CP
,
312 MachineInstr
*CopyMI
) {
313 // FIXME: For now, only eliminate the copy by commuting its def when the
314 // source register is a virtual register. We want to guard against cases
315 // where the copy is a back edge copy and commuting the def lengthen the
316 // live interval of the source register to the entire loop.
317 if (CP
.isPhys() && CP
.isFlipped())
320 // Bail if there is no dst interval.
321 if (!li_
->hasInterval(CP
.getDstReg()))
324 SlotIndex CopyIdx
= li_
->getInstructionIndex(CopyMI
).getDefIndex();
327 li_
->getInterval(CP
.isFlipped() ? CP
.getDstReg() : CP
.getSrcReg());
329 li_
->getInterval(CP
.isFlipped() ? CP
.getSrcReg() : CP
.getDstReg());
331 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
332 // the example above.
333 VNInfo
*BValNo
= IntB
.getVNInfoAt(CopyIdx
);
334 if (!BValNo
|| !BValNo
->isDefByCopy())
337 assert(BValNo
->def
== CopyIdx
&& "Copy doesn't define the value?");
339 // AValNo is the value number in A that defines the copy, A3 in the example.
340 VNInfo
*AValNo
= IntA
.getVNInfoAt(CopyIdx
.getUseIndex());
341 assert(AValNo
&& "COPY source not live");
343 // If other defs can reach uses of this def, then it's not safe to perform
345 if (AValNo
->isPHIDef() || AValNo
->isUnused() || AValNo
->hasPHIKill())
347 MachineInstr
*DefMI
= li_
->getInstructionFromIndex(AValNo
->def
);
350 const TargetInstrDesc
&TID
= DefMI
->getDesc();
351 if (!TID
.isCommutable())
353 // If DefMI is a two-address instruction then commuting it will change the
354 // destination register.
355 int DefIdx
= DefMI
->findRegisterDefOperandIdx(IntA
.reg
);
356 assert(DefIdx
!= -1);
358 if (!DefMI
->isRegTiedToUseOperand(DefIdx
, &UseOpIdx
))
360 unsigned Op1
, Op2
, NewDstIdx
;
361 if (!tii_
->findCommutedOpIndices(DefMI
, Op1
, Op2
))
365 else if (Op2
== UseOpIdx
)
370 MachineOperand
&NewDstMO
= DefMI
->getOperand(NewDstIdx
);
371 unsigned NewReg
= NewDstMO
.getReg();
372 if (NewReg
!= IntB
.reg
|| !NewDstMO
.isKill())
375 // Make sure there are no other definitions of IntB that would reach the
376 // uses which the new definition can reach.
377 if (HasOtherReachingDefs(IntA
, IntB
, AValNo
, BValNo
))
380 // Abort if the aliases of IntB.reg have values that are not simply the
381 // clobbers from the superreg.
382 if (TargetRegisterInfo::isPhysicalRegister(IntB
.reg
))
383 for (const unsigned *AS
= tri_
->getAliasSet(IntB
.reg
); *AS
; ++AS
)
384 if (li_
->hasInterval(*AS
) &&
385 HasOtherReachingDefs(IntA
, li_
->getInterval(*AS
), AValNo
, 0))
388 // If some of the uses of IntA.reg is already coalesced away, return false.
389 // It's not possible to determine whether it's safe to perform the coalescing.
390 for (MachineRegisterInfo::use_nodbg_iterator UI
=
391 mri_
->use_nodbg_begin(IntA
.reg
),
392 UE
= mri_
->use_nodbg_end(); UI
!= UE
; ++UI
) {
393 MachineInstr
*UseMI
= &*UI
;
394 SlotIndex UseIdx
= li_
->getInstructionIndex(UseMI
);
395 LiveInterval::iterator ULR
= IntA
.FindLiveRangeContaining(UseIdx
);
396 if (ULR
== IntA
.end())
398 if (ULR
->valno
== AValNo
&& JoinedCopies
.count(UseMI
))
402 DEBUG(dbgs() << "\tRemoveCopyByCommutingDef: " << AValNo
->def
<< '\t'
405 // At this point we have decided that it is legal to do this
406 // transformation. Start by commuting the instruction.
407 MachineBasicBlock
*MBB
= DefMI
->getParent();
408 MachineInstr
*NewMI
= tii_
->commuteInstruction(DefMI
);
411 if (NewMI
!= DefMI
) {
412 li_
->ReplaceMachineInstrInMaps(DefMI
, NewMI
);
413 MBB
->insert(DefMI
, NewMI
);
416 unsigned OpIdx
= NewMI
->findRegisterUseOperandIdx(IntA
.reg
, false);
417 NewMI
->getOperand(OpIdx
).setIsKill();
419 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
428 // Update uses of IntA of the specific Val# with IntB.
429 for (MachineRegisterInfo::use_iterator UI
= mri_
->use_begin(IntA
.reg
),
430 UE
= mri_
->use_end(); UI
!= UE
;) {
431 MachineOperand
&UseMO
= UI
.getOperand();
432 MachineInstr
*UseMI
= &*UI
;
434 if (JoinedCopies
.count(UseMI
))
436 if (UseMI
->isDebugValue()) {
437 // FIXME These don't have an instruction index. Not clear we have enough
438 // info to decide whether to do this replacement or not. For now do it.
439 UseMO
.setReg(NewReg
);
442 SlotIndex UseIdx
= li_
->getInstructionIndex(UseMI
).getUseIndex();
443 LiveInterval::iterator ULR
= IntA
.FindLiveRangeContaining(UseIdx
);
444 if (ULR
== IntA
.end() || ULR
->valno
!= AValNo
)
446 if (TargetRegisterInfo::isPhysicalRegister(NewReg
))
447 UseMO
.substPhysReg(NewReg
, *tri_
);
449 UseMO
.setReg(NewReg
);
452 if (!UseMI
->isCopy())
454 if (UseMI
->getOperand(0).getReg() != IntB
.reg
||
455 UseMI
->getOperand(0).getSubReg())
458 // This copy will become a noop. If it's defining a new val#, merge it into
460 SlotIndex DefIdx
= UseIdx
.getDefIndex();
461 VNInfo
*DVNI
= IntB
.getVNInfoAt(DefIdx
);
464 DEBUG(dbgs() << "\t\tnoop: " << DefIdx
<< '\t' << *UseMI
);
465 assert(DVNI
->def
== DefIdx
);
466 BValNo
= IntB
.MergeValueNumberInto(BValNo
, DVNI
);
467 JoinedCopies
.insert(UseMI
);
470 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
472 VNInfo
*ValNo
= BValNo
;
473 ValNo
->def
= AValNo
->def
;
475 for (LiveInterval::iterator AI
= IntA
.begin(), AE
= IntA
.end();
477 if (AI
->valno
!= AValNo
) continue;
478 IntB
.addRange(LiveRange(AI
->start
, AI
->end
, ValNo
));
480 DEBUG(dbgs() << "\t\textended: " << IntB
<< '\n');
482 IntA
.removeValNo(AValNo
);
483 DEBUG(dbgs() << "\t\ttrimmed: " << IntA
<< '\n');
488 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
489 /// fallthoughs to SuccMBB.
490 static bool isSameOrFallThroughBB(MachineBasicBlock
*MBB
,
491 MachineBasicBlock
*SuccMBB
,
492 const TargetInstrInfo
*tii_
) {
495 MachineBasicBlock
*TBB
= 0, *FBB
= 0;
496 SmallVector
<MachineOperand
, 4> Cond
;
497 return !tii_
->AnalyzeBranch(*MBB
, TBB
, FBB
, Cond
) && !TBB
&& !FBB
&&
498 MBB
->isSuccessor(SuccMBB
);
501 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
502 /// from a physical register live interval as well as from the live intervals
503 /// of its sub-registers.
504 static void removeRange(LiveInterval
&li
,
505 SlotIndex Start
, SlotIndex End
,
506 LiveIntervals
*li_
, const TargetRegisterInfo
*tri_
) {
507 li
.removeRange(Start
, End
, true);
508 if (TargetRegisterInfo::isPhysicalRegister(li
.reg
)) {
509 for (const unsigned* SR
= tri_
->getSubRegisters(li
.reg
); *SR
; ++SR
) {
510 if (!li_
->hasInterval(*SR
))
512 LiveInterval
&sli
= li_
->getInterval(*SR
);
513 SlotIndex RemoveStart
= Start
;
514 SlotIndex RemoveEnd
= Start
;
516 while (RemoveEnd
!= End
) {
517 LiveInterval::iterator LR
= sli
.FindLiveRangeContaining(RemoveStart
);
520 RemoveEnd
= (LR
->end
< End
) ? LR
->end
: End
;
521 sli
.removeRange(RemoveStart
, RemoveEnd
, true);
522 RemoveStart
= RemoveEnd
;
528 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
529 /// as the copy instruction, trim the live interval to the last use and return
532 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(SlotIndex CopyIdx
,
533 MachineBasicBlock
*CopyMBB
,
535 const LiveRange
*LR
) {
536 SlotIndex MBBStart
= li_
->getMBBStartIdx(CopyMBB
);
537 SlotIndex LastUseIdx
;
538 MachineOperand
*LastUse
=
539 lastRegisterUse(LR
->start
, CopyIdx
.getPrevSlot(), li
.reg
, LastUseIdx
);
541 MachineInstr
*LastUseMI
= LastUse
->getParent();
542 if (!isSameOrFallThroughBB(LastUseMI
->getParent(), CopyMBB
, tii_
)) {
549 // r1025<dead> = r1024<kill>
550 if (MBBStart
< LR
->end
)
551 removeRange(li
, MBBStart
, LR
->end
, li_
, tri_
);
555 // There are uses before the copy, just shorten the live range to the end
557 LastUse
->setIsKill();
558 removeRange(li
, LastUseIdx
.getDefIndex(), LR
->end
, li_
, tri_
);
559 if (LastUseMI
->isCopy()) {
560 MachineOperand
&DefMO
= LastUseMI
->getOperand(0);
561 if (DefMO
.getReg() == li
.reg
&& !DefMO
.getSubReg())
568 if (LR
->start
<= MBBStart
&& LR
->end
> MBBStart
) {
569 if (LR
->start
== li_
->getZeroIndex()) {
570 assert(TargetRegisterInfo::isPhysicalRegister(li
.reg
));
571 // Live-in to the function but dead. Remove it from entry live-in set.
572 mf_
->begin()->removeLiveIn(li
.reg
);
574 // FIXME: Shorten intervals in BBs that reaches this BB.
580 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
581 /// computation, replace the copy by rematerialize the definition.
582 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval
&SrcInt
,
585 MachineInstr
*CopyMI
) {
586 SlotIndex CopyIdx
= li_
->getInstructionIndex(CopyMI
).getUseIndex();
587 LiveInterval::iterator SrcLR
= SrcInt
.FindLiveRangeContaining(CopyIdx
);
588 assert(SrcLR
!= SrcInt
.end() && "Live range not found!");
589 VNInfo
*ValNo
= SrcLR
->valno
;
590 // If other defs can reach uses of this def, then it's not safe to perform
592 if (ValNo
->isPHIDef() || ValNo
->isUnused() || ValNo
->hasPHIKill())
594 MachineInstr
*DefMI
= li_
->getInstructionFromIndex(ValNo
->def
);
597 assert(DefMI
&& "Defining instruction disappeared");
598 const TargetInstrDesc
&TID
= DefMI
->getDesc();
599 if (!TID
.isAsCheapAsAMove())
601 if (!tii_
->isTriviallyReMaterializable(DefMI
, AA
))
603 bool SawStore
= false;
604 if (!DefMI
->isSafeToMove(tii_
, AA
, SawStore
))
606 if (TID
.getNumDefs() != 1)
608 if (!DefMI
->isImplicitDef()) {
609 // Make sure the copy destination register class fits the instruction
610 // definition register class. The mismatch can happen as a result of earlier
611 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
612 const TargetRegisterClass
*RC
= TID
.OpInfo
[0].getRegClass(tri_
);
613 if (TargetRegisterInfo::isVirtualRegister(DstReg
)) {
614 if (mri_
->getRegClass(DstReg
) != RC
)
616 } else if (!RC
->contains(DstReg
))
620 // If destination register has a sub-register index on it, make sure it mtches
621 // the instruction register class.
623 const TargetInstrDesc
&TID
= DefMI
->getDesc();
624 if (TID
.getNumDefs() != 1)
626 const TargetRegisterClass
*DstRC
= mri_
->getRegClass(DstReg
);
627 const TargetRegisterClass
*DstSubRC
=
628 DstRC
->getSubRegisterRegClass(DstSubIdx
);
629 const TargetRegisterClass
*DefRC
= TID
.OpInfo
[0].getRegClass(tri_
);
632 else if (DefRC
!= DstSubRC
)
636 RemoveCopyFlag(DstReg
, CopyMI
);
638 // If copy kills the source register, find the last use and propagate
640 bool checkForDeadDef
= false;
641 MachineBasicBlock
*MBB
= CopyMI
->getParent();
642 if (SrcLR
->end
== CopyIdx
.getDefIndex())
643 if (!TrimLiveIntervalToLastUse(CopyIdx
, MBB
, SrcInt
, SrcLR
)) {
644 checkForDeadDef
= true;
647 MachineBasicBlock::iterator MII
=
648 llvm::next(MachineBasicBlock::iterator(CopyMI
));
649 tii_
->reMaterialize(*MBB
, MII
, DstReg
, DstSubIdx
, DefMI
, *tri_
);
650 MachineInstr
*NewMI
= prior(MII
);
652 if (checkForDeadDef
) {
653 // PR4090 fix: Trim interval failed because there was no use of the
654 // source interval in this MBB. If the def is in this MBB too then we
655 // should mark it dead:
656 if (DefMI
->getParent() == MBB
) {
657 DefMI
->addRegisterDead(SrcInt
.reg
, tri_
);
658 SrcLR
->end
= SrcLR
->start
.getNextSlot();
662 // CopyMI may have implicit operands, transfer them over to the newly
663 // rematerialized instruction. And update implicit def interval valnos.
664 for (unsigned i
= CopyMI
->getDesc().getNumOperands(),
665 e
= CopyMI
->getNumOperands(); i
!= e
; ++i
) {
666 MachineOperand
&MO
= CopyMI
->getOperand(i
);
667 if (MO
.isReg() && MO
.isImplicit())
668 NewMI
->addOperand(MO
);
670 RemoveCopyFlag(MO
.getReg(), CopyMI
);
673 NewMI
->copyImplicitOps(CopyMI
);
674 li_
->ReplaceMachineInstrInMaps(CopyMI
, NewMI
);
675 CopyMI
->eraseFromParent();
676 ReMatCopies
.insert(CopyMI
);
677 ReMatDefs
.insert(DefMI
);
678 DEBUG(dbgs() << "Remat: " << *NewMI
);
683 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
684 /// update the subregister number if it is not zero. If DstReg is a
685 /// physical register and the existing subregister number of the def / use
686 /// being updated is not zero, make sure to set it to the correct physical
689 SimpleRegisterCoalescing::UpdateRegDefsUses(const CoalescerPair
&CP
) {
690 bool DstIsPhys
= CP
.isPhys();
691 unsigned SrcReg
= CP
.getSrcReg();
692 unsigned DstReg
= CP
.getDstReg();
693 unsigned SubIdx
= CP
.getSubIdx();
695 for (MachineRegisterInfo::reg_iterator I
= mri_
->reg_begin(SrcReg
);
696 MachineInstr
*UseMI
= I
.skipInstruction();) {
697 // A PhysReg copy that won't be coalesced can perhaps be rematerialized
700 if (UseMI
->isCopy() &&
701 !UseMI
->getOperand(1).getSubReg() &&
702 !UseMI
->getOperand(0).getSubReg() &&
703 UseMI
->getOperand(1).getReg() == SrcReg
&&
704 UseMI
->getOperand(0).getReg() != SrcReg
&&
705 UseMI
->getOperand(0).getReg() != DstReg
&&
706 !JoinedCopies
.count(UseMI
) &&
707 ReMaterializeTrivialDef(li_
->getInterval(SrcReg
),
708 UseMI
->getOperand(0).getReg(), 0, UseMI
))
712 SmallVector
<unsigned,8> Ops
;
714 tie(Reads
, Writes
) = UseMI
->readsWritesVirtualRegister(SrcReg
, &Ops
);
715 bool Kills
= false, Deads
= false;
717 // Replace SrcReg with DstReg in all UseMI operands.
718 for (unsigned i
= 0, e
= Ops
.size(); i
!= e
; ++i
) {
719 MachineOperand
&MO
= UseMI
->getOperand(Ops
[i
]);
720 Kills
|= MO
.isKill();
721 Deads
|= MO
.isDead();
724 MO
.substPhysReg(DstReg
, *tri_
);
726 MO
.substVirtReg(DstReg
, SubIdx
, *tri_
);
729 // This instruction is a copy that will be removed.
730 if (JoinedCopies
.count(UseMI
))
734 // If UseMI was a simple SrcReg def, make sure we didn't turn it into a
735 // read-modify-write of DstReg.
737 UseMI
->addRegisterDead(DstReg
, tri_
);
738 else if (!Reads
&& Writes
)
739 UseMI
->addRegisterDefined(DstReg
, tri_
);
741 // Kill flags apply to the whole physical register.
742 if (DstIsPhys
&& Kills
)
743 UseMI
->addRegisterKilled(DstReg
, tri_
);
747 dbgs() << "\t\tupdated: ";
748 if (!UseMI
->isDebugValue())
749 dbgs() << li_
->getInstructionIndex(UseMI
) << "\t";
755 /// removeIntervalIfEmpty - Check if the live interval of a physical register
756 /// is empty, if so remove it and also remove the empty intervals of its
757 /// sub-registers. Return true if live interval is removed.
758 static bool removeIntervalIfEmpty(LiveInterval
&li
, LiveIntervals
*li_
,
759 const TargetRegisterInfo
*tri_
) {
761 if (TargetRegisterInfo::isPhysicalRegister(li
.reg
))
762 for (const unsigned* SR
= tri_
->getSubRegisters(li
.reg
); *SR
; ++SR
) {
763 if (!li_
->hasInterval(*SR
))
765 LiveInterval
&sli
= li_
->getInterval(*SR
);
767 li_
->removeInterval(*SR
);
769 li_
->removeInterval(li
.reg
);
775 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
776 /// Return true if live interval is removed.
777 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval
&li
,
778 MachineInstr
*CopyMI
) {
779 SlotIndex CopyIdx
= li_
->getInstructionIndex(CopyMI
);
780 LiveInterval::iterator MLR
=
781 li
.FindLiveRangeContaining(CopyIdx
.getDefIndex());
783 return false; // Already removed by ShortenDeadCopySrcLiveRange.
784 SlotIndex RemoveStart
= MLR
->start
;
785 SlotIndex RemoveEnd
= MLR
->end
;
786 SlotIndex DefIdx
= CopyIdx
.getDefIndex();
787 // Remove the liverange that's defined by this.
788 if (RemoveStart
== DefIdx
&& RemoveEnd
== DefIdx
.getStoreIndex()) {
789 removeRange(li
, RemoveStart
, RemoveEnd
, li_
, tri_
);
790 return removeIntervalIfEmpty(li
, li_
, tri_
);
795 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
796 /// the val# it defines. If the live interval becomes empty, remove it as well.
797 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval
&li
,
798 MachineInstr
*DefMI
) {
799 SlotIndex DefIdx
= li_
->getInstructionIndex(DefMI
).getDefIndex();
800 LiveInterval::iterator MLR
= li
.FindLiveRangeContaining(DefIdx
);
801 if (DefIdx
!= MLR
->valno
->def
)
803 li
.removeValNo(MLR
->valno
);
804 return removeIntervalIfEmpty(li
, li_
, tri_
);
807 void SimpleRegisterCoalescing::RemoveCopyFlag(unsigned DstReg
,
808 const MachineInstr
*CopyMI
) {
809 SlotIndex DefIdx
= li_
->getInstructionIndex(CopyMI
).getDefIndex();
810 if (li_
->hasInterval(DstReg
)) {
811 LiveInterval
&LI
= li_
->getInterval(DstReg
);
812 if (const LiveRange
*LR
= LI
.getLiveRangeContaining(DefIdx
))
813 if (LR
->valno
->def
== DefIdx
)
814 LR
->valno
->setCopy(0);
816 if (!TargetRegisterInfo::isPhysicalRegister(DstReg
))
818 for (const unsigned* AS
= tri_
->getAliasSet(DstReg
); *AS
; ++AS
) {
819 if (!li_
->hasInterval(*AS
))
821 LiveInterval
&LI
= li_
->getInterval(*AS
);
822 if (const LiveRange
*LR
= LI
.getLiveRangeContaining(DefIdx
))
823 if (LR
->valno
->def
== DefIdx
)
824 LR
->valno
->setCopy(0);
828 /// PropagateDeadness - Propagate the dead marker to the instruction which
829 /// defines the val#.
830 static void PropagateDeadness(LiveInterval
&li
, MachineInstr
*CopyMI
,
831 SlotIndex
&LRStart
, LiveIntervals
*li_
,
832 const TargetRegisterInfo
* tri_
) {
833 MachineInstr
*DefMI
=
834 li_
->getInstructionFromIndex(LRStart
.getDefIndex());
835 if (DefMI
&& DefMI
!= CopyMI
) {
836 int DeadIdx
= DefMI
->findRegisterDefOperandIdx(li
.reg
);
838 DefMI
->getOperand(DeadIdx
).setIsDead();
840 DefMI
->addOperand(MachineOperand::CreateReg(li
.reg
,
841 /*def*/true, /*implicit*/true, /*kill*/false, /*dead*/true));
842 LRStart
= LRStart
.getNextSlot();
846 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
847 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
848 /// ends the live range there. If there isn't another use, then this live range
849 /// is dead. Return true if live interval is removed.
851 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval
&li
,
852 MachineInstr
*CopyMI
) {
853 SlotIndex CopyIdx
= li_
->getInstructionIndex(CopyMI
);
854 if (CopyIdx
== SlotIndex()) {
855 // FIXME: special case: function live in. It can be a general case if the
856 // first instruction index starts at > 0 value.
857 assert(TargetRegisterInfo::isPhysicalRegister(li
.reg
));
858 // Live-in to the function but dead. Remove it from entry live-in set.
859 if (mf_
->begin()->isLiveIn(li
.reg
))
860 mf_
->begin()->removeLiveIn(li
.reg
);
861 if (const LiveRange
*LR
= li
.getLiveRangeContaining(CopyIdx
))
862 removeRange(li
, LR
->start
, LR
->end
, li_
, tri_
);
863 return removeIntervalIfEmpty(li
, li_
, tri_
);
866 LiveInterval::iterator LR
=
867 li
.FindLiveRangeContaining(CopyIdx
.getPrevIndex().getStoreIndex());
869 // Livein but defined by a phi.
872 SlotIndex RemoveStart
= LR
->start
;
873 SlotIndex RemoveEnd
= CopyIdx
.getStoreIndex();
874 if (LR
->end
> RemoveEnd
)
875 // More uses past this copy? Nothing to do.
878 // If there is a last use in the same bb, we can't remove the live range.
879 // Shorten the live interval and return.
880 MachineBasicBlock
*CopyMBB
= CopyMI
->getParent();
881 if (TrimLiveIntervalToLastUse(CopyIdx
, CopyMBB
, li
, LR
))
884 // There are other kills of the val#. Nothing to do.
885 if (!li
.isOnlyLROfValNo(LR
))
888 MachineBasicBlock
*StartMBB
= li_
->getMBBFromIndex(RemoveStart
);
889 if (!isSameOrFallThroughBB(StartMBB
, CopyMBB
, tii_
))
890 // If the live range starts in another mbb and the copy mbb is not a fall
891 // through mbb, then we can only cut the range from the beginning of the
893 RemoveStart
= li_
->getMBBStartIdx(CopyMBB
).getNextIndex().getBaseIndex();
895 if (LR
->valno
->def
== RemoveStart
) {
896 // If the def MI defines the val# and this copy is the only kill of the
897 // val#, then propagate the dead marker.
898 PropagateDeadness(li
, CopyMI
, RemoveStart
, li_
, tri_
);
902 removeRange(li
, RemoveStart
, RemoveEnd
, li_
, tri_
);
903 return removeIntervalIfEmpty(li
, li_
, tri_
);
907 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
908 /// two virtual registers from different register classes.
910 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned SrcReg
,
912 const TargetRegisterClass
*SrcRC
,
913 const TargetRegisterClass
*DstRC
,
914 const TargetRegisterClass
*NewRC
) {
915 unsigned NewRCCount
= allocatableRCRegs_
[NewRC
].count();
916 // This heuristics is good enough in practice, but it's obviously not *right*.
917 // 4 is a magic number that works well enough for x86, ARM, etc. It filter
918 // out all but the most restrictive register classes.
919 if (NewRCCount
> 4 ||
920 // Early exit if the function is fairly small, coalesce aggressively if
921 // that's the case. For really special register classes with 3 or
922 // fewer registers, be a bit more careful.
923 (li_
->getFuncInstructionCount() / NewRCCount
) < 8)
925 LiveInterval
&SrcInt
= li_
->getInterval(SrcReg
);
926 LiveInterval
&DstInt
= li_
->getInterval(DstReg
);
927 unsigned SrcSize
= li_
->getApproximateInstructionCount(SrcInt
);
928 unsigned DstSize
= li_
->getApproximateInstructionCount(DstInt
);
929 if (SrcSize
<= NewRCCount
&& DstSize
<= NewRCCount
)
931 // Estimate *register use density*. If it doubles or more, abort.
932 unsigned SrcUses
= std::distance(mri_
->use_nodbg_begin(SrcReg
),
933 mri_
->use_nodbg_end());
934 unsigned DstUses
= std::distance(mri_
->use_nodbg_begin(DstReg
),
935 mri_
->use_nodbg_end());
936 unsigned NewUses
= SrcUses
+ DstUses
;
937 unsigned NewSize
= SrcSize
+ DstSize
;
938 if (SrcRC
!= NewRC
&& SrcSize
> NewRCCount
) {
939 unsigned SrcRCCount
= allocatableRCRegs_
[SrcRC
].count();
940 if (NewUses
*SrcSize
*SrcRCCount
> 2*SrcUses
*NewSize
*NewRCCount
)
943 if (DstRC
!= NewRC
&& DstSize
> NewRCCount
) {
944 unsigned DstRCCount
= allocatableRCRegs_
[DstRC
].count();
945 if (NewUses
*DstSize
*DstRCCount
> 2*DstUses
*NewSize
*NewRCCount
)
952 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
953 /// which are the src/dst of the copy instruction CopyMI. This returns true
954 /// if the copy was successfully coalesced away. If it is not currently
955 /// possible to coalesce this interval, but it may be possible if other
956 /// things get coalesced, then it returns true by reference in 'Again'.
957 bool SimpleRegisterCoalescing::JoinCopy(CopyRec
&TheCopy
, bool &Again
) {
958 MachineInstr
*CopyMI
= TheCopy
.MI
;
961 if (JoinedCopies
.count(CopyMI
) || ReMatCopies
.count(CopyMI
))
962 return false; // Already done.
964 DEBUG(dbgs() << li_
->getInstructionIndex(CopyMI
) << '\t' << *CopyMI
);
966 CoalescerPair
CP(*tii_
, *tri_
);
967 if (!CP
.setRegisters(CopyMI
)) {
968 DEBUG(dbgs() << "\tNot coalescable.\n");
972 // If they are already joined we continue.
973 if (CP
.getSrcReg() == CP
.getDstReg()) {
974 DEBUG(dbgs() << "\tCopy already coalesced.\n");
975 return false; // Not coalescable.
978 if (DisablePhysicalJoin
&& CP
.isPhys()) {
979 DEBUG(dbgs() << "\tPhysical joins disabled.\n");
983 DEBUG(dbgs() << "\tConsidering merging %reg" << CP
.getSrcReg());
987 DEBUG(dbgs() <<" with physreg %" << tri_
->getName(CP
.getDstReg()) << "\n");
988 // Only coalesce to allocatable physreg.
989 if (!li_
->isAllocatable(CP
.getDstReg())) {
990 DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n");
991 return false; // Not coalescable.
995 dbgs() << " with reg%" << CP
.getDstReg();
997 dbgs() << ":" << tri_
->getSubRegIndexName(CP
.getSubIdx());
998 dbgs() << " to " << CP
.getNewRC()->getName() << "\n";
1001 // Avoid constraining virtual register regclass too much.
1002 if (CP
.isCrossClass()) {
1003 if (DisableCrossClassJoin
) {
1004 DEBUG(dbgs() << "\tCross-class joins disabled.\n");
1007 if (!isWinToJoinCrossClass(CP
.getSrcReg(), CP
.getDstReg(),
1008 mri_
->getRegClass(CP
.getSrcReg()),
1009 mri_
->getRegClass(CP
.getDstReg()),
1011 DEBUG(dbgs() << "\tAvoid coalescing to constrained register class: "
1012 << CP
.getNewRC()->getName() << ".\n");
1013 Again
= true; // May be possible to coalesce later.
1018 // When possible, let DstReg be the larger interval.
1019 if (!CP
.getSubIdx() && li_
->getInterval(CP
.getSrcReg()).ranges
.size() >
1020 li_
->getInterval(CP
.getDstReg()).ranges
.size())
1024 // We need to be careful about coalescing a source physical register with a
1025 // virtual register. Once the coalescing is done, it cannot be broken and
1026 // these are not spillable! If the destination interval uses are far away,
1027 // think twice about coalescing them!
1028 // FIXME: Why are we skipping this test for partial copies?
1029 // CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
1030 if (!CP
.isPartial() && CP
.isPhys()) {
1031 LiveInterval
&JoinVInt
= li_
->getInterval(CP
.getSrcReg());
1033 // Don't join with physregs that have a ridiculous number of live
1034 // ranges. The data structure performance is really bad when that
1036 if (li_
->hasInterval(CP
.getDstReg()) &&
1037 li_
->getInterval(CP
.getDstReg()).ranges
.size() > 1000) {
1040 << "\tPhysical register live interval too complicated, abort!\n");
1044 const TargetRegisterClass
*RC
= mri_
->getRegClass(CP
.getSrcReg());
1045 unsigned Threshold
= allocatableRCRegs_
[RC
].count() * 2;
1046 unsigned Length
= li_
->getApproximateInstructionCount(JoinVInt
);
1047 if (Length
> Threshold
&&
1048 std::distance(mri_
->use_nodbg_begin(CP
.getSrcReg()),
1049 mri_
->use_nodbg_end()) * Threshold
< Length
) {
1050 // Before giving up coalescing, if definition of source is defined by
1051 // trivial computation, try rematerializing it.
1052 if (!CP
.isFlipped() &&
1053 ReMaterializeTrivialDef(JoinVInt
, CP
.getDstReg(), 0, CopyMI
))
1057 DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1058 Again
= true; // May be possible to coalesce later.
1063 // Okay, attempt to join these two intervals. On failure, this returns false.
1064 // Otherwise, if one of the intervals being joined is a physreg, this method
1065 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1066 // been modified, so we can use this information below to update aliases.
1067 if (!JoinIntervals(CP
)) {
1068 // Coalescing failed.
1070 // If definition of source is defined by trivial computation, try
1071 // rematerializing it.
1072 if (!CP
.isFlipped() &&
1073 ReMaterializeTrivialDef(li_
->getInterval(CP
.getSrcReg()),
1074 CP
.getDstReg(), 0, CopyMI
))
1077 // If we can eliminate the copy without merging the live ranges, do so now.
1078 if (!CP
.isPartial()) {
1079 if (AdjustCopiesBackFrom(CP
, CopyMI
) ||
1080 RemoveCopyByCommutingDef(CP
, CopyMI
)) {
1081 JoinedCopies
.insert(CopyMI
);
1082 DEBUG(dbgs() << "\tTrivial!\n");
1087 // Otherwise, we are unable to join the intervals.
1088 DEBUG(dbgs() << "\tInterference!\n");
1089 Again
= true; // May be possible to coalesce later.
1093 // Coalescing to a virtual register that is of a sub-register class of the
1094 // other. Make sure the resulting register is set to the right register class.
1095 if (CP
.isCrossClass()) {
1097 mri_
->setRegClass(CP
.getDstReg(), CP
.getNewRC());
1100 // Remember to delete the copy instruction.
1101 JoinedCopies
.insert(CopyMI
);
1103 UpdateRegDefsUses(CP
);
1105 // If we have extended the live range of a physical register, make sure we
1106 // update live-in lists as well.
1108 SmallVector
<MachineBasicBlock
*, 16> BlockSeq
;
1109 // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
1110 // ranges for this, and they are preserved.
1111 LiveInterval
&SrcInt
= li_
->getInterval(CP
.getSrcReg());
1112 for (LiveInterval::const_iterator I
= SrcInt
.begin(), E
= SrcInt
.end();
1114 li_
->findLiveInMBBs(I
->start
, I
->end
, BlockSeq
);
1115 for (unsigned idx
= 0, size
= BlockSeq
.size(); idx
!= size
; ++idx
) {
1116 MachineBasicBlock
&block
= *BlockSeq
[idx
];
1117 if (!block
.isLiveIn(CP
.getDstReg()))
1118 block
.addLiveIn(CP
.getDstReg());
1124 // SrcReg is guarateed to be the register whose live interval that is
1126 li_
->removeInterval(CP
.getSrcReg());
1128 // Update regalloc hint.
1129 tri_
->UpdateRegAllocHint(CP
.getSrcReg(), CP
.getDstReg(), *mf_
);
1132 LiveInterval
&DstInt
= li_
->getInterval(CP
.getDstReg());
1133 dbgs() << "\tJoined. Result = ";
1134 DstInt
.print(dbgs(), tri_
);
1142 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1143 /// compute what the resultant value numbers for each value in the input two
1144 /// ranges will be. This is complicated by copies between the two which can
1145 /// and will commonly cause multiple value numbers to be merged into one.
1147 /// VN is the value number that we're trying to resolve. InstDefiningValue
1148 /// keeps track of the new InstDefiningValue assignment for the result
1149 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1150 /// whether a value in this or other is a copy from the opposite set.
1151 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1152 /// already been assigned.
1154 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1155 /// contains the value number the copy is from.
1157 static unsigned ComputeUltimateVN(VNInfo
*VNI
,
1158 SmallVector
<VNInfo
*, 16> &NewVNInfo
,
1159 DenseMap
<VNInfo
*, VNInfo
*> &ThisFromOther
,
1160 DenseMap
<VNInfo
*, VNInfo
*> &OtherFromThis
,
1161 SmallVector
<int, 16> &ThisValNoAssignments
,
1162 SmallVector
<int, 16> &OtherValNoAssignments
) {
1163 unsigned VN
= VNI
->id
;
1165 // If the VN has already been computed, just return it.
1166 if (ThisValNoAssignments
[VN
] >= 0)
1167 return ThisValNoAssignments
[VN
];
1168 assert(ThisValNoAssignments
[VN
] != -2 && "Cyclic value numbers");
1170 // If this val is not a copy from the other val, then it must be a new value
1171 // number in the destination.
1172 DenseMap
<VNInfo
*, VNInfo
*>::iterator I
= ThisFromOther
.find(VNI
);
1173 if (I
== ThisFromOther
.end()) {
1174 NewVNInfo
.push_back(VNI
);
1175 return ThisValNoAssignments
[VN
] = NewVNInfo
.size()-1;
1177 VNInfo
*OtherValNo
= I
->second
;
1179 // Otherwise, this *is* a copy from the RHS. If the other side has already
1180 // been computed, return it.
1181 if (OtherValNoAssignments
[OtherValNo
->id
] >= 0)
1182 return ThisValNoAssignments
[VN
] = OtherValNoAssignments
[OtherValNo
->id
];
1184 // Mark this value number as currently being computed, then ask what the
1185 // ultimate value # of the other value is.
1186 ThisValNoAssignments
[VN
] = -2;
1187 unsigned UltimateVN
=
1188 ComputeUltimateVN(OtherValNo
, NewVNInfo
, OtherFromThis
, ThisFromOther
,
1189 OtherValNoAssignments
, ThisValNoAssignments
);
1190 return ThisValNoAssignments
[VN
] = UltimateVN
;
1193 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1195 bool SimpleRegisterCoalescing::JoinIntervals(CoalescerPair
&CP
) {
1196 LiveInterval
&RHS
= li_
->getInterval(CP
.getSrcReg());
1197 DEBUG({ dbgs() << "\t\tRHS = "; RHS
.print(dbgs(), tri_
); dbgs() << "\n"; });
1199 // If a live interval is a physical register, check for interference with any
1200 // aliases. The interference check implemented here is a bit more conservative
1201 // than the full interfeence check below. We allow overlapping live ranges
1202 // only when one is a copy of the other.
1204 for (const unsigned *AS
= tri_
->getAliasSet(CP
.getDstReg()); *AS
; ++AS
){
1205 if (!li_
->hasInterval(*AS
))
1207 const LiveInterval
&LHS
= li_
->getInterval(*AS
);
1208 LiveInterval::const_iterator LI
= LHS
.begin();
1209 for (LiveInterval::const_iterator RI
= RHS
.begin(), RE
= RHS
.end();
1211 LI
= std::lower_bound(LI
, LHS
.end(), RI
->start
);
1212 // Does LHS have an overlapping live range starting before RI?
1213 if ((LI
!= LHS
.begin() && LI
[-1].end
> RI
->start
) &&
1214 (RI
->start
!= RI
->valno
->def
||
1215 !CP
.isCoalescable(li_
->getInstructionFromIndex(RI
->start
)))) {
1217 dbgs() << "\t\tInterference from alias: ";
1218 LHS
.print(dbgs(), tri_
);
1219 dbgs() << "\n\t\tOverlap at " << RI
->start
<< " and no copy.\n";
1224 // Check that LHS ranges beginning in this range are copies.
1225 for (; LI
!= LHS
.end() && LI
->start
< RI
->end
; ++LI
) {
1226 if (LI
->start
!= LI
->valno
->def
||
1227 !CP
.isCoalescable(li_
->getInstructionFromIndex(LI
->start
))) {
1229 dbgs() << "\t\tInterference from alias: ";
1230 LHS
.print(dbgs(), tri_
);
1231 dbgs() << "\n\t\tDef at " << LI
->start
<< " is not a copy.\n";
1240 // Compute the final value assignment, assuming that the live ranges can be
1242 SmallVector
<int, 16> LHSValNoAssignments
;
1243 SmallVector
<int, 16> RHSValNoAssignments
;
1244 DenseMap
<VNInfo
*, VNInfo
*> LHSValsDefinedFromRHS
;
1245 DenseMap
<VNInfo
*, VNInfo
*> RHSValsDefinedFromLHS
;
1246 SmallVector
<VNInfo
*, 16> NewVNInfo
;
1248 LiveInterval
&LHS
= li_
->getOrCreateInterval(CP
.getDstReg());
1249 DEBUG({ dbgs() << "\t\tLHS = "; LHS
.print(dbgs(), tri_
); dbgs() << "\n"; });
1251 // Loop over the value numbers of the LHS, seeing if any are defined from
1253 for (LiveInterval::vni_iterator i
= LHS
.vni_begin(), e
= LHS
.vni_end();
1256 if (VNI
->isUnused() || !VNI
->isDefByCopy()) // Src not defined by a copy?
1259 // Never join with a register that has EarlyClobber redefs.
1260 if (VNI
->hasRedefByEC())
1263 // DstReg is known to be a register in the LHS interval. If the src is
1264 // from the RHS interval, we can use its value #.
1265 if (!CP
.isCoalescable(VNI
->getCopy()))
1268 // Figure out the value # from the RHS.
1269 LiveRange
*lr
= RHS
.getLiveRangeContaining(VNI
->def
.getPrevSlot());
1270 // The copy could be to an aliased physreg.
1272 LHSValsDefinedFromRHS
[VNI
] = lr
->valno
;
1275 // Loop over the value numbers of the RHS, seeing if any are defined from
1277 for (LiveInterval::vni_iterator i
= RHS
.vni_begin(), e
= RHS
.vni_end();
1280 if (VNI
->isUnused() || !VNI
->isDefByCopy()) // Src not defined by a copy?
1283 // Never join with a register that has EarlyClobber redefs.
1284 if (VNI
->hasRedefByEC())
1287 // DstReg is known to be a register in the RHS interval. If the src is
1288 // from the LHS interval, we can use its value #.
1289 if (!CP
.isCoalescable(VNI
->getCopy()))
1292 // Figure out the value # from the LHS.
1293 LiveRange
*lr
= LHS
.getLiveRangeContaining(VNI
->def
.getPrevSlot());
1294 // The copy could be to an aliased physreg.
1296 RHSValsDefinedFromLHS
[VNI
] = lr
->valno
;
1299 LHSValNoAssignments
.resize(LHS
.getNumValNums(), -1);
1300 RHSValNoAssignments
.resize(RHS
.getNumValNums(), -1);
1301 NewVNInfo
.reserve(LHS
.getNumValNums() + RHS
.getNumValNums());
1303 for (LiveInterval::vni_iterator i
= LHS
.vni_begin(), e
= LHS
.vni_end();
1306 unsigned VN
= VNI
->id
;
1307 if (LHSValNoAssignments
[VN
] >= 0 || VNI
->isUnused())
1309 ComputeUltimateVN(VNI
, NewVNInfo
,
1310 LHSValsDefinedFromRHS
, RHSValsDefinedFromLHS
,
1311 LHSValNoAssignments
, RHSValNoAssignments
);
1313 for (LiveInterval::vni_iterator i
= RHS
.vni_begin(), e
= RHS
.vni_end();
1316 unsigned VN
= VNI
->id
;
1317 if (RHSValNoAssignments
[VN
] >= 0 || VNI
->isUnused())
1319 // If this value number isn't a copy from the LHS, it's a new number.
1320 if (RHSValsDefinedFromLHS
.find(VNI
) == RHSValsDefinedFromLHS
.end()) {
1321 NewVNInfo
.push_back(VNI
);
1322 RHSValNoAssignments
[VN
] = NewVNInfo
.size()-1;
1326 ComputeUltimateVN(VNI
, NewVNInfo
,
1327 RHSValsDefinedFromLHS
, LHSValsDefinedFromRHS
,
1328 RHSValNoAssignments
, LHSValNoAssignments
);
1331 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1332 // interval lists to see if these intervals are coalescable.
1333 LiveInterval::const_iterator I
= LHS
.begin();
1334 LiveInterval::const_iterator IE
= LHS
.end();
1335 LiveInterval::const_iterator J
= RHS
.begin();
1336 LiveInterval::const_iterator JE
= RHS
.end();
1338 // Skip ahead until the first place of potential sharing.
1339 if (I
!= IE
&& J
!= JE
) {
1340 if (I
->start
< J
->start
) {
1341 I
= std::upper_bound(I
, IE
, J
->start
);
1342 if (I
!= LHS
.begin()) --I
;
1343 } else if (J
->start
< I
->start
) {
1344 J
= std::upper_bound(J
, JE
, I
->start
);
1345 if (J
!= RHS
.begin()) --J
;
1349 while (I
!= IE
&& J
!= JE
) {
1350 // Determine if these two live ranges overlap.
1352 if (I
->start
< J
->start
) {
1353 Overlaps
= I
->end
> J
->start
;
1355 Overlaps
= J
->end
> I
->start
;
1358 // If so, check value # info to determine if they are really different.
1360 // If the live range overlap will map to the same value number in the
1361 // result liverange, we can still coalesce them. If not, we can't.
1362 if (LHSValNoAssignments
[I
->valno
->id
] !=
1363 RHSValNoAssignments
[J
->valno
->id
])
1365 // If it's re-defined by an early clobber somewhere in the live range,
1366 // then conservatively abort coalescing.
1367 if (NewVNInfo
[LHSValNoAssignments
[I
->valno
->id
]]->hasRedefByEC())
1371 if (I
->end
< J
->end
)
1377 // Update kill info. Some live ranges are extended due to copy coalescing.
1378 for (DenseMap
<VNInfo
*, VNInfo
*>::iterator I
= LHSValsDefinedFromRHS
.begin(),
1379 E
= LHSValsDefinedFromRHS
.end(); I
!= E
; ++I
) {
1380 VNInfo
*VNI
= I
->first
;
1381 unsigned LHSValID
= LHSValNoAssignments
[VNI
->id
];
1382 if (VNI
->hasPHIKill())
1383 NewVNInfo
[LHSValID
]->setHasPHIKill(true);
1386 // Update kill info. Some live ranges are extended due to copy coalescing.
1387 for (DenseMap
<VNInfo
*, VNInfo
*>::iterator I
= RHSValsDefinedFromLHS
.begin(),
1388 E
= RHSValsDefinedFromLHS
.end(); I
!= E
; ++I
) {
1389 VNInfo
*VNI
= I
->first
;
1390 unsigned RHSValID
= RHSValNoAssignments
[VNI
->id
];
1391 if (VNI
->hasPHIKill())
1392 NewVNInfo
[RHSValID
]->setHasPHIKill(true);
1395 if (LHSValNoAssignments
.empty())
1396 LHSValNoAssignments
.push_back(-1);
1397 if (RHSValNoAssignments
.empty())
1398 RHSValNoAssignments
.push_back(-1);
1400 // If we get here, we know that we can coalesce the live ranges. Ask the
1401 // intervals to coalesce themselves now.
1402 LHS
.join(RHS
, &LHSValNoAssignments
[0], &RHSValNoAssignments
[0], NewVNInfo
,
1408 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1409 // depth of the basic block (the unsigned), and then on the MBB number.
1410 struct DepthMBBCompare
{
1411 typedef std::pair
<unsigned, MachineBasicBlock
*> DepthMBBPair
;
1412 bool operator()(const DepthMBBPair
&LHS
, const DepthMBBPair
&RHS
) const {
1413 // Deeper loops first
1414 if (LHS
.first
!= RHS
.first
)
1415 return LHS
.first
> RHS
.first
;
1417 // Prefer blocks that are more connected in the CFG. This takes care of
1418 // the most difficult copies first while intervals are short.
1419 unsigned cl
= LHS
.second
->pred_size() + LHS
.second
->succ_size();
1420 unsigned cr
= RHS
.second
->pred_size() + RHS
.second
->succ_size();
1424 // As a last resort, sort by block number.
1425 return LHS
.second
->getNumber() < RHS
.second
->getNumber();
1430 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock
*MBB
,
1431 std::vector
<CopyRec
> &TryAgain
) {
1432 DEBUG(dbgs() << MBB
->getName() << ":\n");
1434 std::vector
<CopyRec
> VirtCopies
;
1435 std::vector
<CopyRec
> PhysCopies
;
1436 std::vector
<CopyRec
> ImpDefCopies
;
1437 for (MachineBasicBlock::iterator MII
= MBB
->begin(), E
= MBB
->end();
1439 MachineInstr
*Inst
= MII
++;
1441 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1442 unsigned SrcReg
, DstReg
;
1443 if (Inst
->isCopy()) {
1444 DstReg
= Inst
->getOperand(0).getReg();
1445 SrcReg
= Inst
->getOperand(1).getReg();
1446 } else if (Inst
->isSubregToReg()) {
1447 DstReg
= Inst
->getOperand(0).getReg();
1448 SrcReg
= Inst
->getOperand(2).getReg();
1452 bool SrcIsPhys
= TargetRegisterInfo::isPhysicalRegister(SrcReg
);
1453 bool DstIsPhys
= TargetRegisterInfo::isPhysicalRegister(DstReg
);
1454 if (li_
->hasInterval(SrcReg
) && li_
->getInterval(SrcReg
).empty())
1455 ImpDefCopies
.push_back(CopyRec(Inst
, 0));
1456 else if (SrcIsPhys
|| DstIsPhys
)
1457 PhysCopies
.push_back(CopyRec(Inst
, 0));
1459 VirtCopies
.push_back(CopyRec(Inst
, 0));
1462 // Try coalescing implicit copies and insert_subreg <undef> first,
1463 // followed by copies to / from physical registers, then finally copies
1464 // from virtual registers to virtual registers.
1465 for (unsigned i
= 0, e
= ImpDefCopies
.size(); i
!= e
; ++i
) {
1466 CopyRec
&TheCopy
= ImpDefCopies
[i
];
1468 if (!JoinCopy(TheCopy
, Again
))
1470 TryAgain
.push_back(TheCopy
);
1472 for (unsigned i
= 0, e
= PhysCopies
.size(); i
!= e
; ++i
) {
1473 CopyRec
&TheCopy
= PhysCopies
[i
];
1475 if (!JoinCopy(TheCopy
, Again
))
1477 TryAgain
.push_back(TheCopy
);
1479 for (unsigned i
= 0, e
= VirtCopies
.size(); i
!= e
; ++i
) {
1480 CopyRec
&TheCopy
= VirtCopies
[i
];
1482 if (!JoinCopy(TheCopy
, Again
))
1484 TryAgain
.push_back(TheCopy
);
1488 void SimpleRegisterCoalescing::joinIntervals() {
1489 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1491 std::vector
<CopyRec
> TryAgainList
;
1492 if (loopInfo
->empty()) {
1493 // If there are no loops in the function, join intervals in function order.
1494 for (MachineFunction::iterator I
= mf_
->begin(), E
= mf_
->end();
1496 CopyCoalesceInMBB(I
, TryAgainList
);
1498 // Otherwise, join intervals in inner loops before other intervals.
1499 // Unfortunately we can't just iterate over loop hierarchy here because
1500 // there may be more MBB's than BB's. Collect MBB's for sorting.
1502 // Join intervals in the function prolog first. We want to join physical
1503 // registers with virtual registers before the intervals got too long.
1504 std::vector
<std::pair
<unsigned, MachineBasicBlock
*> > MBBs
;
1505 for (MachineFunction::iterator I
= mf_
->begin(), E
= mf_
->end();I
!= E
;++I
){
1506 MachineBasicBlock
*MBB
= I
;
1507 MBBs
.push_back(std::make_pair(loopInfo
->getLoopDepth(MBB
), I
));
1510 // Sort by loop depth.
1511 std::sort(MBBs
.begin(), MBBs
.end(), DepthMBBCompare());
1513 // Finally, join intervals in loop nest order.
1514 for (unsigned i
= 0, e
= MBBs
.size(); i
!= e
; ++i
)
1515 CopyCoalesceInMBB(MBBs
[i
].second
, TryAgainList
);
1518 // Joining intervals can allow other intervals to be joined. Iteratively join
1519 // until we make no progress.
1520 bool ProgressMade
= true;
1521 while (ProgressMade
) {
1522 ProgressMade
= false;
1524 for (unsigned i
= 0, e
= TryAgainList
.size(); i
!= e
; ++i
) {
1525 CopyRec
&TheCopy
= TryAgainList
[i
];
1530 bool Success
= JoinCopy(TheCopy
, Again
);
1531 if (Success
|| !Again
) {
1532 TheCopy
.MI
= 0; // Mark this one as done.
1533 ProgressMade
= true;
1539 /// Return true if the two specified registers belong to different register
1540 /// classes. The registers may be either phys or virt regs.
1542 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA
,
1543 unsigned RegB
) const {
1544 // Get the register classes for the first reg.
1545 if (TargetRegisterInfo::isPhysicalRegister(RegA
)) {
1546 assert(TargetRegisterInfo::isVirtualRegister(RegB
) &&
1547 "Shouldn't consider two physregs!");
1548 return !mri_
->getRegClass(RegB
)->contains(RegA
);
1551 // Compare against the regclass for the second reg.
1552 const TargetRegisterClass
*RegClassA
= mri_
->getRegClass(RegA
);
1553 if (TargetRegisterInfo::isVirtualRegister(RegB
)) {
1554 const TargetRegisterClass
*RegClassB
= mri_
->getRegClass(RegB
);
1555 return RegClassA
!= RegClassB
;
1557 return !RegClassA
->contains(RegB
);
1560 /// lastRegisterUse - Returns the last (non-debug) use of the specific register
1561 /// between cycles Start and End or NULL if there are no uses.
1563 SimpleRegisterCoalescing::lastRegisterUse(SlotIndex Start
,
1566 SlotIndex
&UseIdx
) const{
1567 UseIdx
= SlotIndex();
1568 if (TargetRegisterInfo::isVirtualRegister(Reg
)) {
1569 MachineOperand
*LastUse
= NULL
;
1570 for (MachineRegisterInfo::use_nodbg_iterator I
= mri_
->use_nodbg_begin(Reg
),
1571 E
= mri_
->use_nodbg_end(); I
!= E
; ++I
) {
1572 MachineOperand
&Use
= I
.getOperand();
1573 MachineInstr
*UseMI
= Use
.getParent();
1574 if (UseMI
->isIdentityCopy())
1576 SlotIndex Idx
= li_
->getInstructionIndex(UseMI
);
1577 // FIXME: Should this be Idx != UseIdx? SlotIndex() will return something
1578 // that compares higher than any other interval.
1579 if (Idx
>= Start
&& Idx
< End
&& Idx
>= UseIdx
) {
1581 UseIdx
= Idx
.getUseIndex();
1587 SlotIndex s
= Start
;
1588 SlotIndex e
= End
.getPrevSlot().getBaseIndex();
1590 // Skip deleted instructions
1591 MachineInstr
*MI
= li_
->getInstructionFromIndex(e
);
1592 while (e
!= SlotIndex() && e
.getPrevIndex() >= s
&& !MI
) {
1593 e
= e
.getPrevIndex();
1594 MI
= li_
->getInstructionFromIndex(e
);
1596 if (e
< s
|| MI
== NULL
)
1599 // Ignore identity copies.
1600 if (!MI
->isIdentityCopy())
1601 for (unsigned i
= 0, NumOps
= MI
->getNumOperands(); i
!= NumOps
; ++i
) {
1602 MachineOperand
&Use
= MI
->getOperand(i
);
1603 if (Use
.isReg() && Use
.isUse() && Use
.getReg() &&
1604 tri_
->regsOverlap(Use
.getReg(), Reg
)) {
1605 UseIdx
= e
.getUseIndex();
1610 e
= e
.getPrevIndex();
1616 void SimpleRegisterCoalescing::releaseMemory() {
1617 JoinedCopies
.clear();
1618 ReMatCopies
.clear();
1622 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction
&fn
) {
1624 mri_
= &fn
.getRegInfo();
1625 tm_
= &fn
.getTarget();
1626 tri_
= tm_
->getRegisterInfo();
1627 tii_
= tm_
->getInstrInfo();
1628 li_
= &getAnalysis
<LiveIntervals
>();
1629 AA
= &getAnalysis
<AliasAnalysis
>();
1630 loopInfo
= &getAnalysis
<MachineLoopInfo
>();
1632 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1633 << "********** Function: "
1634 << ((Value
*)mf_
->getFunction())->getName() << '\n');
1636 for (TargetRegisterInfo::regclass_iterator I
= tri_
->regclass_begin(),
1637 E
= tri_
->regclass_end(); I
!= E
; ++I
)
1638 allocatableRCRegs_
.insert(std::make_pair(*I
,
1639 tri_
->getAllocatableSet(fn
, *I
)));
1641 // Join (coalesce) intervals if requested.
1642 if (EnableJoining
) {
1645 dbgs() << "********** INTERVALS POST JOINING **********\n";
1646 for (LiveIntervals::iterator I
= li_
->begin(), E
= li_
->end();
1648 I
->second
->print(dbgs(), tri_
);
1654 // Perform a final pass over the instructions and compute spill weights
1655 // and remove identity moves.
1656 SmallVector
<unsigned, 4> DeadDefs
;
1657 for (MachineFunction::iterator mbbi
= mf_
->begin(), mbbe
= mf_
->end();
1658 mbbi
!= mbbe
; ++mbbi
) {
1659 MachineBasicBlock
* mbb
= mbbi
;
1660 for (MachineBasicBlock::iterator mii
= mbb
->begin(), mie
= mbb
->end();
1662 MachineInstr
*MI
= mii
;
1663 if (JoinedCopies
.count(MI
)) {
1664 // Delete all coalesced copies.
1665 bool DoDelete
= true;
1666 assert(MI
->isCopyLike() && "Unrecognized copy instruction");
1667 unsigned SrcReg
= MI
->getOperand(MI
->isSubregToReg() ? 2 : 1).getReg();
1668 if (TargetRegisterInfo::isPhysicalRegister(SrcReg
) &&
1669 MI
->getNumOperands() > 2)
1670 // Do not delete extract_subreg, insert_subreg of physical
1671 // registers unless the definition is dead. e.g.
1672 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1673 // or else the scavenger may complain. LowerSubregs will
1674 // delete them later.
1677 if (MI
->allDefsAreDead()) {
1678 LiveInterval
&li
= li_
->getInterval(SrcReg
);
1679 if (!ShortenDeadCopySrcLiveRange(li
, MI
))
1680 ShortenDeadCopyLiveRange(li
, MI
);
1684 // We need the instruction to adjust liveness, so make it a KILL.
1685 if (MI
->isSubregToReg()) {
1686 MI
->RemoveOperand(3);
1687 MI
->RemoveOperand(1);
1689 MI
->setDesc(tii_
->get(TargetOpcode::KILL
));
1690 mii
= llvm::next(mii
);
1692 li_
->RemoveMachineInstrFromMaps(MI
);
1693 mii
= mbbi
->erase(mii
);
1699 // Now check if this is a remat'ed def instruction which is now dead.
1700 if (ReMatDefs
.count(MI
)) {
1702 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
!= e
; ++i
) {
1703 const MachineOperand
&MO
= MI
->getOperand(i
);
1706 unsigned Reg
= MO
.getReg();
1709 if (TargetRegisterInfo::isVirtualRegister(Reg
))
1710 DeadDefs
.push_back(Reg
);
1713 if (TargetRegisterInfo::isPhysicalRegister(Reg
) ||
1714 !mri_
->use_nodbg_empty(Reg
)) {
1720 while (!DeadDefs
.empty()) {
1721 unsigned DeadDef
= DeadDefs
.back();
1722 DeadDefs
.pop_back();
1723 RemoveDeadDef(li_
->getInterval(DeadDef
), MI
);
1725 li_
->RemoveMachineInstrFromMaps(mii
);
1726 mii
= mbbi
->erase(mii
);
1732 // If the move will be an identity move delete it
1733 if (MI
->isIdentityCopy()) {
1734 unsigned SrcReg
= MI
->getOperand(1).getReg();
1735 if (li_
->hasInterval(SrcReg
)) {
1736 LiveInterval
&RegInt
= li_
->getInterval(SrcReg
);
1737 // If def of this move instruction is dead, remove its live range
1738 // from the destination register's live interval.
1739 if (MI
->allDefsAreDead()) {
1740 if (!ShortenDeadCopySrcLiveRange(RegInt
, MI
))
1741 ShortenDeadCopyLiveRange(RegInt
, MI
);
1744 li_
->RemoveMachineInstrFromMaps(MI
);
1745 mii
= mbbi
->erase(mii
);
1752 // Check for now unnecessary kill flags.
1753 if (li_
->isNotInMIMap(MI
)) continue;
1754 SlotIndex DefIdx
= li_
->getInstructionIndex(MI
).getDefIndex();
1755 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
!= e
; ++i
) {
1756 MachineOperand
&MO
= MI
->getOperand(i
);
1757 if (!MO
.isReg() || !MO
.isKill()) continue;
1758 unsigned reg
= MO
.getReg();
1759 if (!reg
|| !li_
->hasInterval(reg
)) continue;
1760 if (!li_
->getInterval(reg
).killedAt(DefIdx
)) {
1761 MO
.setIsKill(false);
1764 // When leaving a kill flag on a physreg, check if any subregs should
1766 if (!TargetRegisterInfo::isPhysicalRegister(reg
))
1768 for (const unsigned *SR
= tri_
->getSubRegisters(reg
);
1769 unsigned S
= *SR
; ++SR
)
1770 if (li_
->hasInterval(S
) && li_
->getInterval(S
).liveAt(DefIdx
))
1771 MI
->addRegisterDefined(S
, tri_
);
1780 /// print - Implement the dump method.
1781 void SimpleRegisterCoalescing::print(raw_ostream
&O
, const Module
* m
) const {
1785 RegisterCoalescer
* llvm::createSimpleRegisterCoalescer() {
1786 return new SimpleRegisterCoalescing();
1789 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1790 DEFINING_FILE_FOR(SimpleRegisterCoalescing
)