No functionality change. Fix up some whitespace and switch out "" for '' when
[llvm/stm8.git] / lib / CodeGen / SimpleRegisterCoalescing.cpp
blob8a102702ef355debbc4c6a1e634f49ad85898976
1 //===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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 "LiveDebugVariables.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/Value.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/CodeGen/RegisterCoalescer.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/ADT/OwningPtr.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include <algorithm>
40 #include <cmath>
41 using namespace llvm;
43 STATISTIC(numJoins , "Number of interval joins performed");
44 STATISTIC(numCrossRCs , "Number of cross class joins performed");
45 STATISTIC(numCommutes , "Number of instruction commuting performed");
46 STATISTIC(numExtends , "Number of copies extended");
47 STATISTIC(NumReMats , "Number of instructions re-materialized");
48 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
49 STATISTIC(numAborts , "Number of times interval joining aborted");
50 STATISTIC(numDeadValNo, "Number of valno def marked dead");
52 char SimpleRegisterCoalescing::ID = 0;
53 static cl::opt<bool>
54 EnableJoining("join-liveintervals",
55 cl::desc("Coalesce copies (default=true)"),
56 cl::init(true));
58 static cl::opt<bool>
59 DisableCrossClassJoin("disable-cross-class-join",
60 cl::desc("Avoid coalescing cross register class copies"),
61 cl::init(false), cl::Hidden);
63 static cl::opt<bool>
64 DisablePhysicalJoin("disable-physical-join",
65 cl::desc("Avoid coalescing physical register copies"),
66 cl::init(false), cl::Hidden);
68 static cl::opt<bool>
69 VerifyCoalescing("verify-coalescing",
70 cl::desc("Verify machine instrs before and after register coalescing"),
71 cl::Hidden);
73 INITIALIZE_AG_PASS_BEGIN(SimpleRegisterCoalescing, RegisterCoalescer,
74 "simple-register-coalescing", "Simple Register Coalescing",
75 false, false, true)
76 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
77 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
78 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
79 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
80 INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination)
81 INITIALIZE_PASS_DEPENDENCY(PHIElimination)
82 INITIALIZE_PASS_DEPENDENCY(TwoAddressInstructionPass)
83 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
84 INITIALIZE_AG_PASS_END(SimpleRegisterCoalescing, RegisterCoalescer,
85 "simple-register-coalescing", "Simple Register Coalescing",
86 false, false, true)
88 char &llvm::SimpleRegisterCoalescingID = SimpleRegisterCoalescing::ID;
90 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
91 AU.setPreservesCFG();
92 AU.addRequired<AliasAnalysis>();
93 AU.addRequired<LiveIntervals>();
94 AU.addPreserved<LiveIntervals>();
95 AU.addRequired<LiveDebugVariables>();
96 AU.addPreserved<LiveDebugVariables>();
97 AU.addPreserved<SlotIndexes>();
98 AU.addRequired<MachineLoopInfo>();
99 AU.addPreserved<MachineLoopInfo>();
100 AU.addPreservedID(MachineDominatorsID);
101 AU.addPreservedID(StrongPHIEliminationID);
102 AU.addPreservedID(PHIEliminationID);
103 AU.addPreservedID(TwoAddressInstructionPassID);
104 MachineFunctionPass::getAnalysisUsage(AU);
107 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
108 /// being the source and IntB being the dest, thus this defines a value number
109 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
110 /// see if we can merge these two pieces of B into a single value number,
111 /// eliminating a copy. For example:
113 /// A3 = B0
114 /// ...
115 /// B1 = A3 <- this copy
117 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
118 /// value number to be replaced with B0 (which simplifies the B liveinterval).
120 /// This returns true if an interval was modified.
122 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(const CoalescerPair &CP,
123 MachineInstr *CopyMI) {
124 // Bail if there is no dst interval - can happen when merging physical subreg
125 // operations.
126 if (!li_->hasInterval(CP.getDstReg()))
127 return false;
129 LiveInterval &IntA =
130 li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
131 LiveInterval &IntB =
132 li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
133 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
135 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
136 // the example above.
137 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
138 if (BLR == IntB.end()) return false;
139 VNInfo *BValNo = BLR->valno;
141 // Get the location that B is defined at. Two options: either this value has
142 // an unknown definition point or it is defined at CopyIdx. If unknown, we
143 // can't process it.
144 if (!BValNo->isDefByCopy()) return false;
145 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
147 // AValNo is the value number in A that defines the copy, A3 in the example.
148 SlotIndex CopyUseIdx = CopyIdx.getUseIndex();
149 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
150 // The live range might not exist after fun with physreg coalescing.
151 if (ALR == IntA.end()) return false;
152 VNInfo *AValNo = ALR->valno;
153 // If it's re-defined by an early clobber somewhere in the live range, then
154 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
155 // See PR3149:
156 // 172 %ECX<def> = MOV32rr %reg1039<kill>
157 // 180 INLINEASM <es:subl $5,$1
158 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9,
159 // %EAX<kill>,
160 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
161 // 188 %EAX<def> = MOV32rr %EAX<kill>
162 // 196 %ECX<def> = MOV32rr %ECX<kill>
163 // 204 %ECX<def> = MOV32rr %ECX<kill>
164 // 212 %EAX<def> = MOV32rr %EAX<kill>
165 // 220 %EAX<def> = MOV32rr %EAX
166 // 228 %reg1039<def> = MOV32rr %ECX<kill>
167 // The early clobber operand ties ECX input to the ECX def.
169 // The live interval of ECX is represented as this:
170 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
171 // The coalescer has no idea there was a def in the middle of [174,230].
172 if (AValNo->hasRedefByEC())
173 return false;
175 // If AValNo is defined as a copy from IntB, we can potentially process this.
176 // Get the instruction that defines this value number.
177 if (!CP.isCoalescable(AValNo->getCopy()))
178 return false;
180 // Get the LiveRange in IntB that this value number starts with.
181 LiveInterval::iterator ValLR =
182 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
183 if (ValLR == IntB.end())
184 return false;
186 // Make sure that the end of the live range is inside the same block as
187 // CopyMI.
188 MachineInstr *ValLREndInst =
189 li_->getInstructionFromIndex(ValLR->end.getPrevSlot());
190 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
191 return false;
193 // Okay, we now know that ValLR ends in the same block that the CopyMI
194 // live-range starts. If there are no intervening live ranges between them in
195 // IntB, we can merge them.
196 if (ValLR+1 != BLR) return false;
198 // If a live interval is a physical register, conservatively check if any
199 // of its sub-registers is overlapping the live interval of the virtual
200 // register. If so, do not coalesce.
201 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
202 *tri_->getSubRegisters(IntB.reg)) {
203 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
204 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
205 DEBUG({
206 dbgs() << "\t\tInterfere with sub-register ";
207 li_->getInterval(*SR).print(dbgs(), tri_);
209 return false;
213 DEBUG({
214 dbgs() << "Extending: ";
215 IntB.print(dbgs(), tri_);
218 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
219 // We are about to delete CopyMI, so need to remove it as the 'instruction
220 // that defines this value #'. Update the valnum with the new defining
221 // instruction #.
222 BValNo->def = FillerStart;
223 BValNo->setCopy(0);
225 // Okay, we can merge them. We need to insert a new liverange:
226 // [ValLR.end, BLR.begin) of either value number, then we merge the
227 // two value numbers.
228 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
230 // If the IntB live range is assigned to a physical register, and if that
231 // physreg has sub-registers, update their live intervals as well.
232 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
233 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
234 if (!li_->hasInterval(*SR))
235 continue;
236 LiveInterval &SRLI = li_->getInterval(*SR);
237 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
238 SRLI.getNextValue(FillerStart, 0,
239 li_->getVNInfoAllocator())));
243 // Okay, merge "B1" into the same value number as "B0".
244 if (BValNo != ValLR->valno) {
245 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
247 DEBUG({
248 dbgs() << " result = ";
249 IntB.print(dbgs(), tri_);
250 dbgs() << "\n";
253 // If the source instruction was killing the source register before the
254 // merge, unset the isKill marker given the live range has been extended.
255 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
256 if (UIdx != -1) {
257 ValLREndInst->getOperand(UIdx).setIsKill(false);
260 // If the copy instruction was killing the destination register before the
261 // merge, find the last use and trim the live range. That will also add the
262 // isKill marker.
263 if (ALR->end == CopyIdx)
264 TrimLiveIntervalToLastUse(CopyUseIdx, CopyMI->getParent(), IntA, ALR);
266 ++numExtends;
267 return true;
270 /// HasOtherReachingDefs - Return true if there are definitions of IntB
271 /// other than BValNo val# that can reach uses of AValno val# of IntA.
272 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
273 LiveInterval &IntB,
274 VNInfo *AValNo,
275 VNInfo *BValNo) {
276 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
277 AI != AE; ++AI) {
278 if (AI->valno != AValNo) continue;
279 LiveInterval::Ranges::iterator BI =
280 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
281 if (BI != IntB.ranges.begin())
282 --BI;
283 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
284 if (BI->valno == BValNo)
285 continue;
286 if (BI->start <= AI->start && BI->end > AI->start)
287 return true;
288 if (BI->start > AI->start && BI->start < AI->end)
289 return true;
292 return false;
295 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
296 /// IntA being the source and IntB being the dest, thus this defines a value
297 /// number in IntB. If the source value number (in IntA) is defined by a
298 /// commutable instruction and its other operand is coalesced to the copy dest
299 /// register, see if we can transform the copy into a noop by commuting the
300 /// definition. For example,
302 /// A3 = op A2 B0<kill>
303 /// ...
304 /// B1 = A3 <- this copy
305 /// ...
306 /// = op A3 <- more uses
308 /// ==>
310 /// B2 = op B0 A2<kill>
311 /// ...
312 /// B1 = B2 <- now an identify copy
313 /// ...
314 /// = op B2 <- more uses
316 /// This returns true if an interval was modified.
318 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(const CoalescerPair &CP,
319 MachineInstr *CopyMI) {
320 // FIXME: For now, only eliminate the copy by commuting its def when the
321 // source register is a virtual register. We want to guard against cases
322 // where the copy is a back edge copy and commuting the def lengthen the
323 // live interval of the source register to the entire loop.
324 if (CP.isPhys() && CP.isFlipped())
325 return false;
327 // Bail if there is no dst interval.
328 if (!li_->hasInterval(CP.getDstReg()))
329 return false;
331 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
333 LiveInterval &IntA =
334 li_->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
335 LiveInterval &IntB =
336 li_->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
338 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
339 // the example above.
340 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
341 if (!BValNo || !BValNo->isDefByCopy())
342 return false;
344 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
346 // AValNo is the value number in A that defines the copy, A3 in the example.
347 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getUseIndex());
348 assert(AValNo && "COPY source not live");
350 // If other defs can reach uses of this def, then it's not safe to perform
351 // the optimization.
352 if (AValNo->isPHIDef() || AValNo->isUnused() || AValNo->hasPHIKill())
353 return false;
354 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
355 if (!DefMI)
356 return false;
357 const TargetInstrDesc &TID = DefMI->getDesc();
358 if (!TID.isCommutable())
359 return false;
360 // If DefMI is a two-address instruction then commuting it will change the
361 // destination register.
362 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
363 assert(DefIdx != -1);
364 unsigned UseOpIdx;
365 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
366 return false;
367 unsigned Op1, Op2, NewDstIdx;
368 if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
369 return false;
370 if (Op1 == UseOpIdx)
371 NewDstIdx = Op2;
372 else if (Op2 == UseOpIdx)
373 NewDstIdx = Op1;
374 else
375 return false;
377 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
378 unsigned NewReg = NewDstMO.getReg();
379 if (NewReg != IntB.reg || !NewDstMO.isKill())
380 return false;
382 // Make sure there are no other definitions of IntB that would reach the
383 // uses which the new definition can reach.
384 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
385 return false;
387 // Abort if the aliases of IntB.reg have values that are not simply the
388 // clobbers from the superreg.
389 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
390 for (const unsigned *AS = tri_->getAliasSet(IntB.reg); *AS; ++AS)
391 if (li_->hasInterval(*AS) &&
392 HasOtherReachingDefs(IntA, li_->getInterval(*AS), AValNo, 0))
393 return false;
395 // If some of the uses of IntA.reg is already coalesced away, return false.
396 // It's not possible to determine whether it's safe to perform the coalescing.
397 for (MachineRegisterInfo::use_nodbg_iterator UI =
398 mri_->use_nodbg_begin(IntA.reg),
399 UE = mri_->use_nodbg_end(); UI != UE; ++UI) {
400 MachineInstr *UseMI = &*UI;
401 SlotIndex UseIdx = li_->getInstructionIndex(UseMI);
402 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
403 if (ULR == IntA.end())
404 continue;
405 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
406 return false;
409 DEBUG(dbgs() << "\tRemoveCopyByCommutingDef: " << AValNo->def << '\t'
410 << *DefMI);
412 // At this point we have decided that it is legal to do this
413 // transformation. Start by commuting the instruction.
414 MachineBasicBlock *MBB = DefMI->getParent();
415 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
416 if (!NewMI)
417 return false;
418 if (NewMI != DefMI) {
419 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
420 MBB->insert(DefMI, NewMI);
421 MBB->erase(DefMI);
423 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
424 NewMI->getOperand(OpIdx).setIsKill();
426 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
427 // A = or A, B
428 // ...
429 // B = A
430 // ...
431 // C = A<kill>
432 // ...
433 // = B
435 // Update uses of IntA of the specific Val# with IntB.
436 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
437 UE = mri_->use_end(); UI != UE;) {
438 MachineOperand &UseMO = UI.getOperand();
439 MachineInstr *UseMI = &*UI;
440 ++UI;
441 if (JoinedCopies.count(UseMI))
442 continue;
443 if (UseMI->isDebugValue()) {
444 // FIXME These don't have an instruction index. Not clear we have enough
445 // info to decide whether to do this replacement or not. For now do it.
446 UseMO.setReg(NewReg);
447 continue;
449 SlotIndex UseIdx = li_->getInstructionIndex(UseMI).getUseIndex();
450 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
451 if (ULR == IntA.end() || ULR->valno != AValNo)
452 continue;
453 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
454 UseMO.substPhysReg(NewReg, *tri_);
455 else
456 UseMO.setReg(NewReg);
457 if (UseMI == CopyMI)
458 continue;
459 if (!UseMI->isCopy())
460 continue;
461 if (UseMI->getOperand(0).getReg() != IntB.reg ||
462 UseMI->getOperand(0).getSubReg())
463 continue;
465 // This copy will become a noop. If it's defining a new val#, merge it into
466 // BValNo.
467 SlotIndex DefIdx = UseIdx.getDefIndex();
468 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
469 if (!DVNI)
470 continue;
471 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
472 assert(DVNI->def == DefIdx);
473 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
474 JoinedCopies.insert(UseMI);
477 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
478 // is updated.
479 VNInfo *ValNo = BValNo;
480 ValNo->def = AValNo->def;
481 ValNo->setCopy(0);
482 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
483 AI != AE; ++AI) {
484 if (AI->valno != AValNo) continue;
485 IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
487 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
489 IntA.removeValNo(AValNo);
490 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
491 ++numCommutes;
492 return true;
495 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
496 /// fallthoughs to SuccMBB.
497 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
498 MachineBasicBlock *SuccMBB,
499 const TargetInstrInfo *tii_) {
500 if (MBB == SuccMBB)
501 return true;
502 MachineBasicBlock *TBB = 0, *FBB = 0;
503 SmallVector<MachineOperand, 4> Cond;
504 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
505 MBB->isSuccessor(SuccMBB);
508 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
509 /// from a physical register live interval as well as from the live intervals
510 /// of its sub-registers.
511 static void removeRange(LiveInterval &li,
512 SlotIndex Start, SlotIndex End,
513 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
514 li.removeRange(Start, End, true);
515 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
516 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
517 if (!li_->hasInterval(*SR))
518 continue;
519 LiveInterval &sli = li_->getInterval(*SR);
520 SlotIndex RemoveStart = Start;
521 SlotIndex RemoveEnd = Start;
523 while (RemoveEnd != End) {
524 LiveInterval::iterator LR = sli.FindLiveRangeContaining(RemoveStart);
525 if (LR == sli.end())
526 break;
527 RemoveEnd = (LR->end < End) ? LR->end : End;
528 sli.removeRange(RemoveStart, RemoveEnd, true);
529 RemoveStart = RemoveEnd;
535 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
536 /// as the copy instruction, trim the live interval to the last use and return
537 /// true.
538 bool
539 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(SlotIndex CopyIdx,
540 MachineBasicBlock *CopyMBB,
541 LiveInterval &li,
542 const LiveRange *LR) {
543 SlotIndex MBBStart = li_->getMBBStartIdx(CopyMBB);
544 SlotIndex LastUseIdx;
545 MachineOperand *LastUse =
546 lastRegisterUse(LR->start, CopyIdx.getPrevSlot(), li.reg, LastUseIdx);
547 if (LastUse) {
548 MachineInstr *LastUseMI = LastUse->getParent();
549 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
550 // r1024 = op
551 // ...
552 // BB1:
553 // = r1024
555 // BB2:
556 // r1025<dead> = r1024<kill>
557 if (MBBStart < LR->end)
558 removeRange(li, MBBStart, LR->end, li_, tri_);
559 return true;
562 // There are uses before the copy, just shorten the live range to the end
563 // of last use.
564 LastUse->setIsKill();
565 removeRange(li, LastUseIdx.getDefIndex(), LR->end, li_, tri_);
566 if (LastUseMI->isCopy()) {
567 MachineOperand &DefMO = LastUseMI->getOperand(0);
568 if (DefMO.getReg() == li.reg && !DefMO.getSubReg())
569 DefMO.setIsDead();
571 return true;
574 // Is it livein?
575 if (LR->start <= MBBStart && LR->end > MBBStart) {
576 if (LR->start == li_->getZeroIndex()) {
577 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
578 // Live-in to the function but dead. Remove it from entry live-in set.
579 mf_->begin()->removeLiveIn(li.reg);
581 // FIXME: Shorten intervals in BBs that reaches this BB.
584 return false;
587 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
588 /// computation, replace the copy by rematerialize the definition.
589 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
590 bool preserveSrcInt,
591 unsigned DstReg,
592 unsigned DstSubIdx,
593 MachineInstr *CopyMI) {
594 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI).getUseIndex();
595 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
596 assert(SrcLR != SrcInt.end() && "Live range not found!");
597 VNInfo *ValNo = SrcLR->valno;
598 // If other defs can reach uses of this def, then it's not safe to perform
599 // the optimization.
600 if (ValNo->isPHIDef() || ValNo->isUnused() || ValNo->hasPHIKill())
601 return false;
602 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
603 if (!DefMI)
604 return false;
605 assert(DefMI && "Defining instruction disappeared");
606 const TargetInstrDesc &TID = DefMI->getDesc();
607 if (!TID.isAsCheapAsAMove())
608 return false;
609 if (!tii_->isTriviallyReMaterializable(DefMI, AA))
610 return false;
611 bool SawStore = false;
612 if (!DefMI->isSafeToMove(tii_, AA, SawStore))
613 return false;
614 if (TID.getNumDefs() != 1)
615 return false;
616 if (!DefMI->isImplicitDef()) {
617 // Make sure the copy destination register class fits the instruction
618 // definition register class. The mismatch can happen as a result of earlier
619 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
620 const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
621 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
622 if (mri_->getRegClass(DstReg) != RC)
623 return false;
624 } else if (!RC->contains(DstReg))
625 return false;
628 // If destination register has a sub-register index on it, make sure it
629 // matches the instruction register class.
630 if (DstSubIdx) {
631 const TargetInstrDesc &TID = DefMI->getDesc();
632 if (TID.getNumDefs() != 1)
633 return false;
634 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
635 const TargetRegisterClass *DstSubRC =
636 DstRC->getSubRegisterRegClass(DstSubIdx);
637 const TargetRegisterClass *DefRC = TID.OpInfo[0].getRegClass(tri_);
638 if (DefRC == DstRC)
639 DstSubIdx = 0;
640 else if (DefRC != DstSubRC)
641 return false;
644 RemoveCopyFlag(DstReg, CopyMI);
646 MachineBasicBlock *MBB = CopyMI->getParent();
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 // CopyMI may have implicit operands, transfer them over to the newly
653 // rematerialized instruction. And update implicit def interval valnos.
654 for (unsigned i = CopyMI->getDesc().getNumOperands(),
655 e = CopyMI->getNumOperands(); i != e; ++i) {
656 MachineOperand &MO = CopyMI->getOperand(i);
657 if (MO.isReg() && MO.isImplicit())
658 NewMI->addOperand(MO);
659 if (MO.isDef())
660 RemoveCopyFlag(MO.getReg(), CopyMI);
663 NewMI->copyImplicitOps(CopyMI);
664 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
665 CopyMI->eraseFromParent();
666 ReMatCopies.insert(CopyMI);
667 ReMatDefs.insert(DefMI);
668 DEBUG(dbgs() << "Remat: " << *NewMI);
669 ++NumReMats;
671 // The source interval can become smaller because we removed a use.
672 if (preserveSrcInt)
673 li_->shrinkToUses(&SrcInt);
675 return true;
678 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
679 /// update the subregister number if it is not zero. If DstReg is a
680 /// physical register and the existing subregister number of the def / use
681 /// being updated is not zero, make sure to set it to the correct physical
682 /// subregister.
683 void
684 SimpleRegisterCoalescing::UpdateRegDefsUses(const CoalescerPair &CP) {
685 bool DstIsPhys = CP.isPhys();
686 unsigned SrcReg = CP.getSrcReg();
687 unsigned DstReg = CP.getDstReg();
688 unsigned SubIdx = CP.getSubIdx();
690 // Update LiveDebugVariables.
691 ldv_->renameRegister(SrcReg, DstReg, SubIdx);
693 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg);
694 MachineInstr *UseMI = I.skipInstruction();) {
695 // A PhysReg copy that won't be coalesced can perhaps be rematerialized
696 // instead.
697 if (DstIsPhys) {
698 if (UseMI->isCopy() &&
699 !UseMI->getOperand(1).getSubReg() &&
700 !UseMI->getOperand(0).getSubReg() &&
701 UseMI->getOperand(1).getReg() == SrcReg &&
702 UseMI->getOperand(0).getReg() != SrcReg &&
703 UseMI->getOperand(0).getReg() != DstReg &&
704 !JoinedCopies.count(UseMI) &&
705 ReMaterializeTrivialDef(li_->getInterval(SrcReg), false,
706 UseMI->getOperand(0).getReg(), 0, UseMI))
707 continue;
710 SmallVector<unsigned,8> Ops;
711 bool Reads, Writes;
712 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
713 bool Kills = false, Deads = false;
715 // Replace SrcReg with DstReg in all UseMI operands.
716 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
717 MachineOperand &MO = UseMI->getOperand(Ops[i]);
718 Kills |= MO.isKill();
719 Deads |= MO.isDead();
721 if (DstIsPhys)
722 MO.substPhysReg(DstReg, *tri_);
723 else
724 MO.substVirtReg(DstReg, SubIdx, *tri_);
727 // This instruction is a copy that will be removed.
728 if (JoinedCopies.count(UseMI))
729 continue;
731 if (SubIdx) {
732 // If UseMI was a simple SrcReg def, make sure we didn't turn it into a
733 // read-modify-write of DstReg.
734 if (Deads)
735 UseMI->addRegisterDead(DstReg, tri_);
736 else if (!Reads && Writes)
737 UseMI->addRegisterDefined(DstReg, tri_);
739 // Kill flags apply to the whole physical register.
740 if (DstIsPhys && Kills)
741 UseMI->addRegisterKilled(DstReg, tri_);
744 DEBUG({
745 dbgs() << "\t\tupdated: ";
746 if (!UseMI->isDebugValue())
747 dbgs() << li_->getInstructionIndex(UseMI) << "\t";
748 dbgs() << *UseMI;
753 /// removeIntervalIfEmpty - Check if the live interval of a physical register
754 /// is empty, if so remove it and also remove the empty intervals of its
755 /// sub-registers. Return true if live interval is removed.
756 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
757 const TargetRegisterInfo *tri_) {
758 if (li.empty()) {
759 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
760 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
761 if (!li_->hasInterval(*SR))
762 continue;
763 LiveInterval &sli = li_->getInterval(*SR);
764 if (sli.empty())
765 li_->removeInterval(*SR);
767 li_->removeInterval(li.reg);
768 return true;
770 return false;
773 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
774 /// Return true if live interval is removed.
775 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
776 MachineInstr *CopyMI) {
777 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
778 LiveInterval::iterator MLR =
779 li.FindLiveRangeContaining(CopyIdx.getDefIndex());
780 if (MLR == li.end())
781 return false; // Already removed by ShortenDeadCopySrcLiveRange.
782 SlotIndex RemoveStart = MLR->start;
783 SlotIndex RemoveEnd = MLR->end;
784 SlotIndex DefIdx = CopyIdx.getDefIndex();
785 // Remove the liverange that's defined by this.
786 if (RemoveStart == DefIdx && RemoveEnd == DefIdx.getStoreIndex()) {
787 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
788 return removeIntervalIfEmpty(li, li_, tri_);
790 return false;
793 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
794 /// the val# it defines. If the live interval becomes empty, remove it as well.
795 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
796 MachineInstr *DefMI) {
797 SlotIndex DefIdx = li_->getInstructionIndex(DefMI).getDefIndex();
798 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
799 if (DefIdx != MLR->valno->def)
800 return false;
801 li.removeValNo(MLR->valno);
802 return removeIntervalIfEmpty(li, li_, tri_);
805 void SimpleRegisterCoalescing::RemoveCopyFlag(unsigned DstReg,
806 const MachineInstr *CopyMI) {
807 SlotIndex DefIdx = li_->getInstructionIndex(CopyMI).getDefIndex();
808 if (li_->hasInterval(DstReg)) {
809 LiveInterval &LI = li_->getInterval(DstReg);
810 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
811 if (LR->valno->def == DefIdx)
812 LR->valno->setCopy(0);
814 if (!TargetRegisterInfo::isPhysicalRegister(DstReg))
815 return;
816 for (const unsigned* AS = tri_->getAliasSet(DstReg); *AS; ++AS) {
817 if (!li_->hasInterval(*AS))
818 continue;
819 LiveInterval &LI = li_->getInterval(*AS);
820 if (const LiveRange *LR = LI.getLiveRangeContaining(DefIdx))
821 if (LR->valno->def == DefIdx)
822 LR->valno->setCopy(0);
826 /// PropagateDeadness - Propagate the dead marker to the instruction which
827 /// defines the val#.
828 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
829 SlotIndex &LRStart, LiveIntervals *li_,
830 const TargetRegisterInfo* tri_) {
831 MachineInstr *DefMI =
832 li_->getInstructionFromIndex(LRStart.getDefIndex());
833 if (DefMI && DefMI != CopyMI) {
834 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg);
835 if (DeadIdx != -1)
836 DefMI->getOperand(DeadIdx).setIsDead();
837 else
838 DefMI->addOperand(MachineOperand::CreateReg(li.reg,
839 /*def*/true, /*implicit*/true, /*kill*/false, /*dead*/true));
840 LRStart = LRStart.getNextSlot();
844 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
845 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
846 /// ends the live range there. If there isn't another use, then this live range
847 /// is dead. Return true if live interval is removed.
848 bool
849 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
850 MachineInstr *CopyMI) {
851 SlotIndex CopyIdx = li_->getInstructionIndex(CopyMI);
852 if (CopyIdx == SlotIndex()) {
853 // FIXME: special case: function live in. It can be a general case if the
854 // first instruction index starts at > 0 value.
855 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
856 // Live-in to the function but dead. Remove it from entry live-in set.
857 if (mf_->begin()->isLiveIn(li.reg))
858 mf_->begin()->removeLiveIn(li.reg);
859 if (const LiveRange *LR = li.getLiveRangeContaining(CopyIdx))
860 removeRange(li, LR->start, LR->end, li_, tri_);
861 return removeIntervalIfEmpty(li, li_, tri_);
864 LiveInterval::iterator LR =
865 li.FindLiveRangeContaining(CopyIdx.getPrevIndex().getStoreIndex());
866 if (LR == li.end())
867 // Livein but defined by a phi.
868 return false;
870 SlotIndex RemoveStart = LR->start;
871 SlotIndex RemoveEnd = CopyIdx.getStoreIndex();
872 if (LR->end > RemoveEnd)
873 // More uses past this copy? Nothing to do.
874 return false;
876 // If there is a last use in the same bb, we can't remove the live range.
877 // Shorten the live interval and return.
878 MachineBasicBlock *CopyMBB = CopyMI->getParent();
879 if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
880 return false;
882 // There are other kills of the val#. Nothing to do.
883 if (!li.isOnlyLROfValNo(LR))
884 return false;
886 MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
887 if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
888 // If the live range starts in another mbb and the copy mbb is not a fall
889 // through mbb, then we can only cut the range from the beginning of the
890 // copy mbb.
891 RemoveStart = li_->getMBBStartIdx(CopyMBB).getNextIndex().getBaseIndex();
893 if (LR->valno->def == RemoveStart) {
894 // If the def MI defines the val# and this copy is the only kill of the
895 // val#, then propagate the dead marker.
896 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
897 ++numDeadValNo;
900 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
901 return removeIntervalIfEmpty(li, li_, tri_);
905 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
906 /// two virtual registers from different register classes.
907 bool
908 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned SrcReg,
909 unsigned DstReg,
910 const TargetRegisterClass *SrcRC,
911 const TargetRegisterClass *DstRC,
912 const TargetRegisterClass *NewRC) {
913 unsigned NewRCCount = allocatableRCRegs_[NewRC].count();
914 // This heuristics is good enough in practice, but it's obviously not *right*.
915 // 4 is a magic number that works well enough for x86, ARM, etc. It filter
916 // out all but the most restrictive register classes.
917 if (NewRCCount > 4 ||
918 // Early exit if the function is fairly small, coalesce aggressively if
919 // that's the case. For really special register classes with 3 or
920 // fewer registers, be a bit more careful.
921 (li_->getFuncInstructionCount() / NewRCCount) < 8)
922 return true;
923 LiveInterval &SrcInt = li_->getInterval(SrcReg);
924 LiveInterval &DstInt = li_->getInterval(DstReg);
925 unsigned SrcSize = li_->getApproximateInstructionCount(SrcInt);
926 unsigned DstSize = li_->getApproximateInstructionCount(DstInt);
927 if (SrcSize <= NewRCCount && DstSize <= NewRCCount)
928 return true;
929 // Estimate *register use density*. If it doubles or more, abort.
930 unsigned SrcUses = std::distance(mri_->use_nodbg_begin(SrcReg),
931 mri_->use_nodbg_end());
932 unsigned DstUses = std::distance(mri_->use_nodbg_begin(DstReg),
933 mri_->use_nodbg_end());
934 unsigned NewUses = SrcUses + DstUses;
935 unsigned NewSize = SrcSize + DstSize;
936 if (SrcRC != NewRC && SrcSize > NewRCCount) {
937 unsigned SrcRCCount = allocatableRCRegs_[SrcRC].count();
938 if (NewUses*SrcSize*SrcRCCount > 2*SrcUses*NewSize*NewRCCount)
939 return false;
941 if (DstRC != NewRC && DstSize > NewRCCount) {
942 unsigned DstRCCount = allocatableRCRegs_[DstRC].count();
943 if (NewUses*DstSize*DstRCCount > 2*DstUses*NewSize*NewRCCount)
944 return false;
946 return true;
950 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
951 /// which are the src/dst of the copy instruction CopyMI. This returns true
952 /// if the copy was successfully coalesced away. If it is not currently
953 /// possible to coalesce this interval, but it may be possible if other
954 /// things get coalesced, then it returns true by reference in 'Again'.
955 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
956 MachineInstr *CopyMI = TheCopy.MI;
958 Again = false;
959 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
960 return false; // Already done.
962 DEBUG(dbgs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
964 CoalescerPair CP(*tii_, *tri_);
965 if (!CP.setRegisters(CopyMI)) {
966 DEBUG(dbgs() << "\tNot coalescable.\n");
967 return false;
970 // If they are already joined we continue.
971 if (CP.getSrcReg() == CP.getDstReg()) {
972 DEBUG(dbgs() << "\tCopy already coalesced.\n");
973 return false; // Not coalescable.
976 if (DisablePhysicalJoin && CP.isPhys()) {
977 DEBUG(dbgs() << "\tPhysical joins disabled.\n");
978 return false;
981 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), tri_));
983 // Enforce policies.
984 if (CP.isPhys()) {
985 DEBUG(dbgs() <<" with physreg " << PrintReg(CP.getDstReg(), tri_) << "\n");
986 // Only coalesce to allocatable physreg.
987 if (!li_->isAllocatable(CP.getDstReg())) {
988 DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n");
989 return false; // Not coalescable.
991 } else {
992 DEBUG(dbgs() << " with " << PrintReg(CP.getDstReg(), tri_, CP.getSubIdx())
993 << " to " << CP.getNewRC()->getName() << "\n");
995 // Avoid constraining virtual register regclass too much.
996 if (CP.isCrossClass()) {
997 if (DisableCrossClassJoin) {
998 DEBUG(dbgs() << "\tCross-class joins disabled.\n");
999 return false;
1001 if (!isWinToJoinCrossClass(CP.getSrcReg(), CP.getDstReg(),
1002 mri_->getRegClass(CP.getSrcReg()),
1003 mri_->getRegClass(CP.getDstReg()),
1004 CP.getNewRC())) {
1005 DEBUG(dbgs() << "\tAvoid coalescing to constrained register class: "
1006 << CP.getNewRC()->getName() << ".\n");
1007 Again = true; // May be possible to coalesce later.
1008 return false;
1012 // When possible, let DstReg be the larger interval.
1013 if (!CP.getSubIdx() && li_->getInterval(CP.getSrcReg()).ranges.size() >
1014 li_->getInterval(CP.getDstReg()).ranges.size())
1015 CP.flip();
1018 // We need to be careful about coalescing a source physical register with a
1019 // virtual register. Once the coalescing is done, it cannot be broken and
1020 // these are not spillable! If the destination interval uses are far away,
1021 // think twice about coalescing them!
1022 // FIXME: Why are we skipping this test for partial copies?
1023 // CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
1024 if (!CP.isPartial() && CP.isPhys()) {
1025 LiveInterval &JoinVInt = li_->getInterval(CP.getSrcReg());
1027 // Don't join with physregs that have a ridiculous number of live
1028 // ranges. The data structure performance is really bad when that
1029 // happens.
1030 if (li_->hasInterval(CP.getDstReg()) &&
1031 li_->getInterval(CP.getDstReg()).ranges.size() > 1000) {
1032 ++numAborts;
1033 DEBUG(dbgs()
1034 << "\tPhysical register live interval too complicated, abort!\n");
1035 return false;
1038 const TargetRegisterClass *RC = mri_->getRegClass(CP.getSrcReg());
1039 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1040 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1041 if (Length > Threshold) {
1042 // Before giving up coalescing, if definition of source is defined by
1043 // trivial computation, try rematerializing it.
1044 if (!CP.isFlipped() &&
1045 ReMaterializeTrivialDef(JoinVInt, true, CP.getDstReg(), 0, CopyMI))
1046 return true;
1048 ++numAborts;
1049 DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1050 Again = true; // May be possible to coalesce later.
1051 return false;
1055 // Okay, attempt to join these two intervals. On failure, this returns false.
1056 // Otherwise, if one of the intervals being joined is a physreg, this method
1057 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1058 // been modified, so we can use this information below to update aliases.
1059 if (!JoinIntervals(CP)) {
1060 // Coalescing failed.
1062 // If definition of source is defined by trivial computation, try
1063 // rematerializing it.
1064 if (!CP.isFlipped() &&
1065 ReMaterializeTrivialDef(li_->getInterval(CP.getSrcReg()), true,
1066 CP.getDstReg(), 0, CopyMI))
1067 return true;
1069 // If we can eliminate the copy without merging the live ranges, do so now.
1070 if (!CP.isPartial()) {
1071 if (AdjustCopiesBackFrom(CP, CopyMI) ||
1072 RemoveCopyByCommutingDef(CP, CopyMI)) {
1073 JoinedCopies.insert(CopyMI);
1074 DEBUG(dbgs() << "\tTrivial!\n");
1075 return true;
1079 // Otherwise, we are unable to join the intervals.
1080 DEBUG(dbgs() << "\tInterference!\n");
1081 Again = true; // May be possible to coalesce later.
1082 return false;
1085 // Coalescing to a virtual register that is of a sub-register class of the
1086 // other. Make sure the resulting register is set to the right register class.
1087 if (CP.isCrossClass()) {
1088 ++numCrossRCs;
1089 mri_->setRegClass(CP.getDstReg(), CP.getNewRC());
1092 // Remember to delete the copy instruction.
1093 JoinedCopies.insert(CopyMI);
1095 UpdateRegDefsUses(CP);
1097 // If we have extended the live range of a physical register, make sure we
1098 // update live-in lists as well.
1099 if (CP.isPhys()) {
1100 SmallVector<MachineBasicBlock*, 16> BlockSeq;
1101 // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
1102 // ranges for this, and they are preserved.
1103 LiveInterval &SrcInt = li_->getInterval(CP.getSrcReg());
1104 for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
1105 I != E; ++I ) {
1106 li_->findLiveInMBBs(I->start, I->end, BlockSeq);
1107 for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1108 MachineBasicBlock &block = *BlockSeq[idx];
1109 if (!block.isLiveIn(CP.getDstReg()))
1110 block.addLiveIn(CP.getDstReg());
1112 BlockSeq.clear();
1116 // SrcReg is guarateed to be the register whose live interval that is
1117 // being merged.
1118 li_->removeInterval(CP.getSrcReg());
1120 // Update regalloc hint.
1121 tri_->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *mf_);
1123 DEBUG({
1124 LiveInterval &DstInt = li_->getInterval(CP.getDstReg());
1125 dbgs() << "\tJoined. Result = ";
1126 DstInt.print(dbgs(), tri_);
1127 dbgs() << "\n";
1130 ++numJoins;
1131 return true;
1134 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1135 /// compute what the resultant value numbers for each value in the input two
1136 /// ranges will be. This is complicated by copies between the two which can
1137 /// and will commonly cause multiple value numbers to be merged into one.
1139 /// VN is the value number that we're trying to resolve. InstDefiningValue
1140 /// keeps track of the new InstDefiningValue assignment for the result
1141 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1142 /// whether a value in this or other is a copy from the opposite set.
1143 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1144 /// already been assigned.
1146 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1147 /// contains the value number the copy is from.
1149 static unsigned ComputeUltimateVN(VNInfo *VNI,
1150 SmallVector<VNInfo*, 16> &NewVNInfo,
1151 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1152 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1153 SmallVector<int, 16> &ThisValNoAssignments,
1154 SmallVector<int, 16> &OtherValNoAssignments) {
1155 unsigned VN = VNI->id;
1157 // If the VN has already been computed, just return it.
1158 if (ThisValNoAssignments[VN] >= 0)
1159 return ThisValNoAssignments[VN];
1160 assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1162 // If this val is not a copy from the other val, then it must be a new value
1163 // number in the destination.
1164 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1165 if (I == ThisFromOther.end()) {
1166 NewVNInfo.push_back(VNI);
1167 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1169 VNInfo *OtherValNo = I->second;
1171 // Otherwise, this *is* a copy from the RHS. If the other side has already
1172 // been computed, return it.
1173 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1174 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1176 // Mark this value number as currently being computed, then ask what the
1177 // ultimate value # of the other value is.
1178 ThisValNoAssignments[VN] = -2;
1179 unsigned UltimateVN =
1180 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1181 OtherValNoAssignments, ThisValNoAssignments);
1182 return ThisValNoAssignments[VN] = UltimateVN;
1185 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1186 /// returns false.
1187 bool SimpleRegisterCoalescing::JoinIntervals(CoalescerPair &CP) {
1188 LiveInterval &RHS = li_->getInterval(CP.getSrcReg());
1189 DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), tri_); dbgs() << "\n"; });
1191 // If a live interval is a physical register, check for interference with any
1192 // aliases. The interference check implemented here is a bit more conservative
1193 // than the full interfeence check below. We allow overlapping live ranges
1194 // only when one is a copy of the other.
1195 if (CP.isPhys()) {
1196 for (const unsigned *AS = tri_->getAliasSet(CP.getDstReg()); *AS; ++AS){
1197 if (!li_->hasInterval(*AS))
1198 continue;
1199 const LiveInterval &LHS = li_->getInterval(*AS);
1200 LiveInterval::const_iterator LI = LHS.begin();
1201 for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1202 RI != RE; ++RI) {
1203 LI = std::lower_bound(LI, LHS.end(), RI->start);
1204 // Does LHS have an overlapping live range starting before RI?
1205 if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1206 (RI->start != RI->valno->def ||
1207 !CP.isCoalescable(li_->getInstructionFromIndex(RI->start)))) {
1208 DEBUG({
1209 dbgs() << "\t\tInterference from alias: ";
1210 LHS.print(dbgs(), tri_);
1211 dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1213 return false;
1216 // Check that LHS ranges beginning in this range are copies.
1217 for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1218 if (LI->start != LI->valno->def ||
1219 !CP.isCoalescable(li_->getInstructionFromIndex(LI->start))) {
1220 DEBUG({
1221 dbgs() << "\t\tInterference from alias: ";
1222 LHS.print(dbgs(), tri_);
1223 dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1225 return false;
1232 // Compute the final value assignment, assuming that the live ranges can be
1233 // coalesced.
1234 SmallVector<int, 16> LHSValNoAssignments;
1235 SmallVector<int, 16> RHSValNoAssignments;
1236 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1237 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1238 SmallVector<VNInfo*, 16> NewVNInfo;
1240 LiveInterval &LHS = li_->getOrCreateInterval(CP.getDstReg());
1241 DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), tri_); dbgs() << "\n"; });
1243 // Loop over the value numbers of the LHS, seeing if any are defined from
1244 // the RHS.
1245 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1246 i != e; ++i) {
1247 VNInfo *VNI = *i;
1248 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy?
1249 continue;
1251 // Never join with a register that has EarlyClobber redefs.
1252 if (VNI->hasRedefByEC())
1253 return false;
1255 // DstReg is known to be a register in the LHS interval. If the src is
1256 // from the RHS interval, we can use its value #.
1257 if (!CP.isCoalescable(VNI->getCopy()))
1258 continue;
1260 // Figure out the value # from the RHS.
1261 LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1262 // The copy could be to an aliased physreg.
1263 if (!lr) continue;
1264 LHSValsDefinedFromRHS[VNI] = lr->valno;
1267 // Loop over the value numbers of the RHS, seeing if any are defined from
1268 // the LHS.
1269 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1270 i != e; ++i) {
1271 VNInfo *VNI = *i;
1272 if (VNI->isUnused() || !VNI->isDefByCopy()) // Src not defined by a copy?
1273 continue;
1275 // Never join with a register that has EarlyClobber redefs.
1276 if (VNI->hasRedefByEC())
1277 return false;
1279 // DstReg is known to be a register in the RHS interval. If the src is
1280 // from the LHS interval, we can use its value #.
1281 if (!CP.isCoalescable(VNI->getCopy()))
1282 continue;
1284 // Figure out the value # from the LHS.
1285 LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1286 // The copy could be to an aliased physreg.
1287 if (!lr) continue;
1288 RHSValsDefinedFromLHS[VNI] = lr->valno;
1291 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1292 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1293 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1295 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1296 i != e; ++i) {
1297 VNInfo *VNI = *i;
1298 unsigned VN = VNI->id;
1299 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1300 continue;
1301 ComputeUltimateVN(VNI, NewVNInfo,
1302 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1303 LHSValNoAssignments, RHSValNoAssignments);
1305 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1306 i != e; ++i) {
1307 VNInfo *VNI = *i;
1308 unsigned VN = VNI->id;
1309 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1310 continue;
1311 // If this value number isn't a copy from the LHS, it's a new number.
1312 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1313 NewVNInfo.push_back(VNI);
1314 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1315 continue;
1318 ComputeUltimateVN(VNI, NewVNInfo,
1319 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1320 RHSValNoAssignments, LHSValNoAssignments);
1323 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1324 // interval lists to see if these intervals are coalescable.
1325 LiveInterval::const_iterator I = LHS.begin();
1326 LiveInterval::const_iterator IE = LHS.end();
1327 LiveInterval::const_iterator J = RHS.begin();
1328 LiveInterval::const_iterator JE = RHS.end();
1330 // Skip ahead until the first place of potential sharing.
1331 if (I != IE && J != JE) {
1332 if (I->start < J->start) {
1333 I = std::upper_bound(I, IE, J->start);
1334 if (I != LHS.begin()) --I;
1335 } else if (J->start < I->start) {
1336 J = std::upper_bound(J, JE, I->start);
1337 if (J != RHS.begin()) --J;
1341 while (I != IE && J != JE) {
1342 // Determine if these two live ranges overlap.
1343 bool Overlaps;
1344 if (I->start < J->start) {
1345 Overlaps = I->end > J->start;
1346 } else {
1347 Overlaps = J->end > I->start;
1350 // If so, check value # info to determine if they are really different.
1351 if (Overlaps) {
1352 // If the live range overlap will map to the same value number in the
1353 // result liverange, we can still coalesce them. If not, we can't.
1354 if (LHSValNoAssignments[I->valno->id] !=
1355 RHSValNoAssignments[J->valno->id])
1356 return false;
1357 // If it's re-defined by an early clobber somewhere in the live range,
1358 // then conservatively abort coalescing.
1359 if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
1360 return false;
1363 if (I->end < J->end)
1364 ++I;
1365 else
1366 ++J;
1369 // Update kill info. Some live ranges are extended due to copy coalescing.
1370 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1371 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1372 VNInfo *VNI = I->first;
1373 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1374 if (VNI->hasPHIKill())
1375 NewVNInfo[LHSValID]->setHasPHIKill(true);
1378 // Update kill info. Some live ranges are extended due to copy coalescing.
1379 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1380 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1381 VNInfo *VNI = I->first;
1382 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1383 if (VNI->hasPHIKill())
1384 NewVNInfo[RHSValID]->setHasPHIKill(true);
1387 if (LHSValNoAssignments.empty())
1388 LHSValNoAssignments.push_back(-1);
1389 if (RHSValNoAssignments.empty())
1390 RHSValNoAssignments.push_back(-1);
1392 // If we get here, we know that we can coalesce the live ranges. Ask the
1393 // intervals to coalesce themselves now.
1394 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1395 mri_);
1396 return true;
1399 namespace {
1400 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1401 // depth of the basic block (the unsigned), and then on the MBB number.
1402 struct DepthMBBCompare {
1403 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1404 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1405 // Deeper loops first
1406 if (LHS.first != RHS.first)
1407 return LHS.first > RHS.first;
1409 // Prefer blocks that are more connected in the CFG. This takes care of
1410 // the most difficult copies first while intervals are short.
1411 unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1412 unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1413 if (cl != cr)
1414 return cl > cr;
1416 // As a last resort, sort by block number.
1417 return LHS.second->getNumber() < RHS.second->getNumber();
1422 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1423 std::vector<CopyRec> &TryAgain) {
1424 DEBUG(dbgs() << MBB->getName() << ":\n");
1426 SmallVector<CopyRec, 8> VirtCopies;
1427 SmallVector<CopyRec, 8> PhysCopies;
1428 SmallVector<CopyRec, 8> ImpDefCopies;
1429 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1430 MII != E;) {
1431 MachineInstr *Inst = MII++;
1433 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1434 unsigned SrcReg, DstReg;
1435 if (Inst->isCopy()) {
1436 DstReg = Inst->getOperand(0).getReg();
1437 SrcReg = Inst->getOperand(1).getReg();
1438 } else if (Inst->isSubregToReg()) {
1439 DstReg = Inst->getOperand(0).getReg();
1440 SrcReg = Inst->getOperand(2).getReg();
1441 } else
1442 continue;
1444 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1445 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1446 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1447 ImpDefCopies.push_back(CopyRec(Inst, 0));
1448 else if (SrcIsPhys || DstIsPhys)
1449 PhysCopies.push_back(CopyRec(Inst, 0));
1450 else
1451 VirtCopies.push_back(CopyRec(Inst, 0));
1454 // Try coalescing implicit copies and insert_subreg <undef> first,
1455 // followed by copies to / from physical registers, then finally copies
1456 // from virtual registers to virtual registers.
1457 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1458 CopyRec &TheCopy = ImpDefCopies[i];
1459 bool Again = false;
1460 if (!JoinCopy(TheCopy, Again))
1461 if (Again)
1462 TryAgain.push_back(TheCopy);
1464 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1465 CopyRec &TheCopy = PhysCopies[i];
1466 bool Again = false;
1467 if (!JoinCopy(TheCopy, Again))
1468 if (Again)
1469 TryAgain.push_back(TheCopy);
1471 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1472 CopyRec &TheCopy = VirtCopies[i];
1473 bool Again = false;
1474 if (!JoinCopy(TheCopy, Again))
1475 if (Again)
1476 TryAgain.push_back(TheCopy);
1480 void SimpleRegisterCoalescing::joinIntervals() {
1481 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1483 std::vector<CopyRec> TryAgainList;
1484 if (loopInfo->empty()) {
1485 // If there are no loops in the function, join intervals in function order.
1486 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1487 I != E; ++I)
1488 CopyCoalesceInMBB(I, TryAgainList);
1489 } else {
1490 // Otherwise, join intervals in inner loops before other intervals.
1491 // Unfortunately we can't just iterate over loop hierarchy here because
1492 // there may be more MBB's than BB's. Collect MBB's for sorting.
1494 // Join intervals in the function prolog first. We want to join physical
1495 // registers with virtual registers before the intervals got too long.
1496 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1497 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1498 MachineBasicBlock *MBB = I;
1499 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1502 // Sort by loop depth.
1503 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1505 // Finally, join intervals in loop nest order.
1506 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1507 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1510 // Joining intervals can allow other intervals to be joined. Iteratively join
1511 // until we make no progress.
1512 bool ProgressMade = true;
1513 while (ProgressMade) {
1514 ProgressMade = false;
1516 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1517 CopyRec &TheCopy = TryAgainList[i];
1518 if (!TheCopy.MI)
1519 continue;
1521 bool Again = false;
1522 bool Success = JoinCopy(TheCopy, Again);
1523 if (Success || !Again) {
1524 TheCopy.MI = 0; // Mark this one as done.
1525 ProgressMade = true;
1531 /// Return true if the two specified registers belong to different register
1532 /// classes. The registers may be either phys or virt regs.
1533 bool
1534 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
1535 unsigned RegB) const {
1536 // Get the register classes for the first reg.
1537 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1538 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1539 "Shouldn't consider two physregs!");
1540 return !mri_->getRegClass(RegB)->contains(RegA);
1543 // Compare against the regclass for the second reg.
1544 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
1545 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
1546 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
1547 return RegClassA != RegClassB;
1549 return !RegClassA->contains(RegB);
1552 /// lastRegisterUse - Returns the last (non-debug) use of the specific register
1553 /// between cycles Start and End or NULL if there are no uses.
1554 MachineOperand *
1555 SimpleRegisterCoalescing::lastRegisterUse(SlotIndex Start,
1556 SlotIndex End,
1557 unsigned Reg,
1558 SlotIndex &UseIdx) const{
1559 UseIdx = SlotIndex();
1560 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1561 MachineOperand *LastUse = NULL;
1562 for (MachineRegisterInfo::use_nodbg_iterator I = mri_->use_nodbg_begin(Reg),
1563 E = mri_->use_nodbg_end(); I != E; ++I) {
1564 MachineOperand &Use = I.getOperand();
1565 MachineInstr *UseMI = Use.getParent();
1566 if (UseMI->isIdentityCopy())
1567 continue;
1568 SlotIndex Idx = li_->getInstructionIndex(UseMI);
1569 if (Idx >= Start && Idx < End && (!UseIdx.isValid() || Idx >= UseIdx)) {
1570 LastUse = &Use;
1571 UseIdx = Idx.getUseIndex();
1574 return LastUse;
1577 SlotIndex s = Start;
1578 SlotIndex e = End.getPrevSlot().getBaseIndex();
1579 while (e >= s) {
1580 // Skip deleted instructions
1581 MachineInstr *MI = li_->getInstructionFromIndex(e);
1582 while (e != SlotIndex() && e.getPrevIndex() >= s && !MI) {
1583 e = e.getPrevIndex();
1584 MI = li_->getInstructionFromIndex(e);
1586 if (e < s || MI == NULL)
1587 return NULL;
1589 // Ignore identity copies.
1590 if (!MI->isIdentityCopy())
1591 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1592 MachineOperand &Use = MI->getOperand(i);
1593 if (Use.isReg() && Use.isUse() && Use.getReg() &&
1594 tri_->regsOverlap(Use.getReg(), Reg)) {
1595 UseIdx = e.getUseIndex();
1596 return &Use;
1600 e = e.getPrevIndex();
1603 return NULL;
1606 void SimpleRegisterCoalescing::releaseMemory() {
1607 JoinedCopies.clear();
1608 ReMatCopies.clear();
1609 ReMatDefs.clear();
1612 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1613 mf_ = &fn;
1614 mri_ = &fn.getRegInfo();
1615 tm_ = &fn.getTarget();
1616 tri_ = tm_->getRegisterInfo();
1617 tii_ = tm_->getInstrInfo();
1618 li_ = &getAnalysis<LiveIntervals>();
1619 ldv_ = &getAnalysis<LiveDebugVariables>();
1620 AA = &getAnalysis<AliasAnalysis>();
1621 loopInfo = &getAnalysis<MachineLoopInfo>();
1623 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1624 << "********** Function: "
1625 << ((Value*)mf_->getFunction())->getName() << '\n');
1627 if (VerifyCoalescing)
1628 mf_->verify(this, "Before register coalescing");
1630 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1631 E = tri_->regclass_end(); I != E; ++I)
1632 allocatableRCRegs_.insert(std::make_pair(*I,
1633 tri_->getAllocatableSet(fn, *I)));
1635 // Join (coalesce) intervals if requested.
1636 if (EnableJoining) {
1637 joinIntervals();
1638 DEBUG({
1639 dbgs() << "********** INTERVALS POST JOINING **********\n";
1640 for (LiveIntervals::iterator I = li_->begin(), E = li_->end();
1641 I != E; ++I){
1642 I->second->print(dbgs(), tri_);
1643 dbgs() << "\n";
1648 // Perform a final pass over the instructions and compute spill weights
1649 // and remove identity moves.
1650 SmallVector<unsigned, 4> DeadDefs;
1651 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1652 mbbi != mbbe; ++mbbi) {
1653 MachineBasicBlock* mbb = mbbi;
1654 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1655 mii != mie; ) {
1656 MachineInstr *MI = mii;
1657 if (JoinedCopies.count(MI)) {
1658 // Delete all coalesced copies.
1659 bool DoDelete = true;
1660 assert(MI->isCopyLike() && "Unrecognized copy instruction");
1661 unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1662 if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1663 MI->getNumOperands() > 2)
1664 // Do not delete extract_subreg, insert_subreg of physical
1665 // registers unless the definition is dead. e.g.
1666 // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1667 // or else the scavenger may complain. LowerSubregs will
1668 // delete them later.
1669 DoDelete = false;
1671 if (MI->allDefsAreDead()) {
1672 if (li_->hasInterval(SrcReg)) {
1673 LiveInterval &li = li_->getInterval(SrcReg);
1674 if (!ShortenDeadCopySrcLiveRange(li, MI))
1675 ShortenDeadCopyLiveRange(li, MI);
1677 DoDelete = true;
1679 if (!DoDelete) {
1680 // We need the instruction to adjust liveness, so make it a KILL.
1681 if (MI->isSubregToReg()) {
1682 MI->RemoveOperand(3);
1683 MI->RemoveOperand(1);
1685 MI->setDesc(tii_->get(TargetOpcode::KILL));
1686 mii = llvm::next(mii);
1687 } else {
1688 li_->RemoveMachineInstrFromMaps(MI);
1689 mii = mbbi->erase(mii);
1690 ++numPeep;
1692 continue;
1695 // Now check if this is a remat'ed def instruction which is now dead.
1696 if (ReMatDefs.count(MI)) {
1697 bool isDead = true;
1698 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1699 const MachineOperand &MO = MI->getOperand(i);
1700 if (!MO.isReg())
1701 continue;
1702 unsigned Reg = MO.getReg();
1703 if (!Reg)
1704 continue;
1705 if (TargetRegisterInfo::isVirtualRegister(Reg))
1706 DeadDefs.push_back(Reg);
1707 if (MO.isDead())
1708 continue;
1709 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1710 !mri_->use_nodbg_empty(Reg)) {
1711 isDead = false;
1712 break;
1715 if (isDead) {
1716 while (!DeadDefs.empty()) {
1717 unsigned DeadDef = DeadDefs.back();
1718 DeadDefs.pop_back();
1719 RemoveDeadDef(li_->getInterval(DeadDef), MI);
1721 li_->RemoveMachineInstrFromMaps(mii);
1722 mii = mbbi->erase(mii);
1723 continue;
1724 } else
1725 DeadDefs.clear();
1728 // If the move will be an identity move delete it
1729 if (MI->isIdentityCopy()) {
1730 unsigned SrcReg = MI->getOperand(1).getReg();
1731 if (li_->hasInterval(SrcReg)) {
1732 LiveInterval &RegInt = li_->getInterval(SrcReg);
1733 // If def of this move instruction is dead, remove its live range
1734 // from the destination register's live interval.
1735 if (MI->allDefsAreDead()) {
1736 if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
1737 ShortenDeadCopyLiveRange(RegInt, MI);
1740 li_->RemoveMachineInstrFromMaps(MI);
1741 mii = mbbi->erase(mii);
1742 ++numPeep;
1743 continue;
1746 ++mii;
1748 // Check for now unnecessary kill flags.
1749 if (li_->isNotInMIMap(MI)) continue;
1750 SlotIndex DefIdx = li_->getInstructionIndex(MI).getDefIndex();
1751 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1752 MachineOperand &MO = MI->getOperand(i);
1753 if (!MO.isReg() || !MO.isKill()) continue;
1754 unsigned reg = MO.getReg();
1755 if (!reg || !li_->hasInterval(reg)) continue;
1756 if (!li_->getInterval(reg).killedAt(DefIdx)) {
1757 MO.setIsKill(false);
1758 continue;
1760 // When leaving a kill flag on a physreg, check if any subregs should
1761 // remain alive.
1762 if (!TargetRegisterInfo::isPhysicalRegister(reg))
1763 continue;
1764 for (const unsigned *SR = tri_->getSubRegisters(reg);
1765 unsigned S = *SR; ++SR)
1766 if (li_->hasInterval(S) && li_->getInterval(S).liveAt(DefIdx))
1767 MI->addRegisterDefined(S, tri_);
1772 DEBUG(dump());
1773 DEBUG(ldv_->dump());
1774 if (VerifyCoalescing)
1775 mf_->verify(this, "After register coalescing");
1776 return true;
1779 /// print - Implement the dump method.
1780 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
1781 li_->print(O, m);
1784 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1785 return new SimpleRegisterCoalescing();
1788 // Make sure that anything that uses RegisterCoalescer pulls in this file...
1789 DEFINING_FILE_FOR(SimpleRegisterCoalescing)