Remove -new-coalescer-heuristic. It's not useful.
[llvm/avr.git] / lib / CodeGen / SimpleRegisterCoalescing.cpp
blob1288e3053aaba840accb90c11c1da8adfe598b9b
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 "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/Value.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/RegisterCoalescer.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetOptions.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include <algorithm>
37 #include <cmath>
38 using namespace llvm;
40 STATISTIC(numJoins , "Number of interval joins performed");
41 STATISTIC(numCrossRCs , "Number of cross class joins performed");
42 STATISTIC(numCommutes , "Number of instruction commuting performed");
43 STATISTIC(numExtends , "Number of copies extended");
44 STATISTIC(NumReMats , "Number of instructions re-materialized");
45 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
46 STATISTIC(numAborts , "Number of times interval joining aborted");
47 STATISTIC(numDeadValNo, "Number of valno def marked dead");
49 char SimpleRegisterCoalescing::ID = 0;
50 static cl::opt<bool>
51 EnableJoining("join-liveintervals",
52 cl::desc("Coalesce copies (default=true)"),
53 cl::init(true));
55 static cl::opt<bool>
56 DisableCrossClassJoin("disable-cross-class-join",
57 cl::desc("Avoid coalescing cross register class copies"),
58 cl::init(false), cl::Hidden);
60 static cl::opt<bool>
61 PhysJoinTweak("tweak-phys-join-heuristics",
62 cl::desc("Tweak heuristics for joining phys reg with vr"),
63 cl::init(false), cl::Hidden);
65 static RegisterPass<SimpleRegisterCoalescing>
66 X("simple-register-coalescing", "Simple Register Coalescing");
68 // Declare that we implement the RegisterCoalescer interface
69 static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
71 const PassInfo *const llvm::SimpleRegisterCoalescingID = &X;
73 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
74 AU.setPreservesCFG();
75 AU.addRequired<LiveIntervals>();
76 AU.addPreserved<LiveIntervals>();
77 AU.addRequired<MachineLoopInfo>();
78 AU.addPreserved<MachineLoopInfo>();
79 AU.addPreservedID(MachineDominatorsID);
80 if (StrongPHIElim)
81 AU.addPreservedID(StrongPHIEliminationID);
82 else
83 AU.addPreservedID(PHIEliminationID);
84 AU.addPreservedID(TwoAddressInstructionPassID);
85 MachineFunctionPass::getAnalysisUsage(AU);
88 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
89 /// being the source and IntB being the dest, thus this defines a value number
90 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
91 /// see if we can merge these two pieces of B into a single value number,
92 /// eliminating a copy. For example:
93 ///
94 /// A3 = B0
95 /// ...
96 /// B1 = A3 <- this copy
97 ///
98 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
99 /// value number to be replaced with B0 (which simplifies the B liveinterval).
101 /// This returns true if an interval was modified.
103 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
104 LiveInterval &IntB,
105 MachineInstr *CopyMI) {
106 MachineInstrIndex CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
108 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
109 // the example above.
110 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
111 assert(BLR != IntB.end() && "Live range not found!");
112 VNInfo *BValNo = BLR->valno;
114 // Get the location that B is defined at. Two options: either this value has
115 // an unknown definition point or it is defined at CopyIdx. If unknown, we
116 // can't process it.
117 if (!BValNo->getCopy()) return false;
118 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
120 // AValNo is the value number in A that defines the copy, A3 in the example.
121 MachineInstrIndex CopyUseIdx = li_->getUseIndex(CopyIdx);
122 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
123 assert(ALR != IntA.end() && "Live range not found!");
124 VNInfo *AValNo = ALR->valno;
125 // If it's re-defined by an early clobber somewhere in the live range, then
126 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
127 // See PR3149:
128 // 172 %ECX<def> = MOV32rr %reg1039<kill>
129 // 180 INLINEASM <es:subl $5,$1
130 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9, %EAX<kill>,
131 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
132 // 188 %EAX<def> = MOV32rr %EAX<kill>
133 // 196 %ECX<def> = MOV32rr %ECX<kill>
134 // 204 %ECX<def> = MOV32rr %ECX<kill>
135 // 212 %EAX<def> = MOV32rr %EAX<kill>
136 // 220 %EAX<def> = MOV32rr %EAX
137 // 228 %reg1039<def> = MOV32rr %ECX<kill>
138 // The early clobber operand ties ECX input to the ECX def.
140 // The live interval of ECX is represented as this:
141 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
142 // The coalescer has no idea there was a def in the middle of [174,230].
143 if (AValNo->hasRedefByEC())
144 return false;
146 // If AValNo is defined as a copy from IntB, we can potentially process this.
147 // Get the instruction that defines this value number.
148 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
149 if (!SrcReg) return false; // Not defined by a copy.
151 // If the value number is not defined by a copy instruction, ignore it.
153 // If the source register comes from an interval other than IntB, we can't
154 // handle this.
155 if (SrcReg != IntB.reg) return false;
157 // Get the LiveRange in IntB that this value number starts with.
158 LiveInterval::iterator ValLR =
159 IntB.FindLiveRangeContaining(li_->getPrevSlot(AValNo->def));
160 assert(ValLR != IntB.end() && "Live range not found!");
162 // Make sure that the end of the live range is inside the same block as
163 // CopyMI.
164 MachineInstr *ValLREndInst =
165 li_->getInstructionFromIndex(li_->getPrevSlot(ValLR->end));
166 if (!ValLREndInst ||
167 ValLREndInst->getParent() != CopyMI->getParent()) return false;
169 // Okay, we now know that ValLR ends in the same block that the CopyMI
170 // live-range starts. If there are no intervening live ranges between them in
171 // IntB, we can merge them.
172 if (ValLR+1 != BLR) return false;
174 // If a live interval is a physical register, conservatively check if any
175 // of its sub-registers is overlapping the live interval of the virtual
176 // register. If so, do not coalesce.
177 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
178 *tri_->getSubRegisters(IntB.reg)) {
179 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
180 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
181 DEBUG({
182 errs() << "Interfere with sub-register ";
183 li_->getInterval(*SR).print(errs(), tri_);
185 return false;
189 DEBUG({
190 errs() << "\nExtending: ";
191 IntB.print(errs(), tri_);
194 MachineInstrIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
195 // We are about to delete CopyMI, so need to remove it as the 'instruction
196 // that defines this value #'. Update the the valnum with the new defining
197 // instruction #.
198 BValNo->def = FillerStart;
199 BValNo->setCopy(0);
201 // Okay, we can merge them. We need to insert a new liverange:
202 // [ValLR.end, BLR.begin) of either value number, then we merge the
203 // two value numbers.
204 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
206 // If the IntB live range is assigned to a physical register, and if that
207 // physreg has sub-registers, update their live intervals as well.
208 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
209 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
210 LiveInterval &SRLI = li_->getInterval(*SR);
211 SRLI.addRange(LiveRange(FillerStart, FillerEnd,
212 SRLI.getNextValue(FillerStart, 0, true,
213 li_->getVNInfoAllocator())));
217 // Okay, merge "B1" into the same value number as "B0".
218 if (BValNo != ValLR->valno) {
219 IntB.addKills(ValLR->valno, BValNo->kills);
220 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
222 DEBUG({
223 errs() << " result = ";
224 IntB.print(errs(), tri_);
225 errs() << "\n";
228 // If the source instruction was killing the source register before the
229 // merge, unset the isKill marker given the live range has been extended.
230 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
231 if (UIdx != -1) {
232 ValLREndInst->getOperand(UIdx).setIsKill(false);
233 ValLR->valno->removeKill(FillerStart);
236 // If the copy instruction was killing the destination register before the
237 // merge, find the last use and trim the live range. That will also add the
238 // isKill marker.
239 if (CopyMI->killsRegister(IntA.reg))
240 TrimLiveIntervalToLastUse(CopyUseIdx, CopyMI->getParent(), IntA, ALR);
242 ++numExtends;
243 return true;
246 /// HasOtherReachingDefs - Return true if there are definitions of IntB
247 /// other than BValNo val# that can reach uses of AValno val# of IntA.
248 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
249 LiveInterval &IntB,
250 VNInfo *AValNo,
251 VNInfo *BValNo) {
252 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
253 AI != AE; ++AI) {
254 if (AI->valno != AValNo) continue;
255 LiveInterval::Ranges::iterator BI =
256 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
257 if (BI != IntB.ranges.begin())
258 --BI;
259 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
260 if (BI->valno == BValNo)
261 continue;
262 if (BI->start <= AI->start && BI->end > AI->start)
263 return true;
264 if (BI->start > AI->start && BI->start < AI->end)
265 return true;
268 return false;
271 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
272 /// being the source and IntB being the dest, thus this defines a value number
273 /// in IntB. If the source value number (in IntA) is defined by a commutable
274 /// instruction and its other operand is coalesced to the copy dest register,
275 /// see if we can transform the copy into a noop by commuting the definition. For
276 /// example,
278 /// A3 = op A2 B0<kill>
279 /// ...
280 /// B1 = A3 <- this copy
281 /// ...
282 /// = op A3 <- more uses
284 /// ==>
286 /// B2 = op B0 A2<kill>
287 /// ...
288 /// B1 = B2 <- now an identify copy
289 /// ...
290 /// = op B2 <- more uses
292 /// This returns true if an interval was modified.
294 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
295 LiveInterval &IntB,
296 MachineInstr *CopyMI) {
297 MachineInstrIndex CopyIdx =
298 li_->getDefIndex(li_->getInstructionIndex(CopyMI));
300 // FIXME: For now, only eliminate the copy by commuting its def when the
301 // source register is a virtual register. We want to guard against cases
302 // where the copy is a back edge copy and commuting the def lengthen the
303 // live interval of the source register to the entire loop.
304 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
305 return false;
307 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
308 // the example above.
309 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
310 assert(BLR != IntB.end() && "Live range not found!");
311 VNInfo *BValNo = BLR->valno;
313 // Get the location that B is defined at. Two options: either this value has
314 // an unknown definition point or it is defined at CopyIdx. If unknown, we
315 // can't process it.
316 if (!BValNo->getCopy()) return false;
317 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
319 // AValNo is the value number in A that defines the copy, A3 in the example.
320 LiveInterval::iterator ALR =
321 IntA.FindLiveRangeContaining(li_->getPrevSlot(CopyIdx));
323 assert(ALR != IntA.end() && "Live range not found!");
324 VNInfo *AValNo = ALR->valno;
325 // If other defs can reach uses of this def, then it's not safe to perform
326 // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
327 // tested?
328 if (AValNo->isPHIDef() || !AValNo->isDefAccurate() ||
329 AValNo->isUnused() || AValNo->hasPHIKill())
330 return false;
331 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
332 const TargetInstrDesc &TID = DefMI->getDesc();
333 if (!TID.isCommutable())
334 return false;
335 // If DefMI is a two-address instruction then commuting it will change the
336 // destination register.
337 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
338 assert(DefIdx != -1);
339 unsigned UseOpIdx;
340 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
341 return false;
342 unsigned Op1, Op2, NewDstIdx;
343 if (!tii_->findCommutedOpIndices(DefMI, Op1, Op2))
344 return false;
345 if (Op1 == UseOpIdx)
346 NewDstIdx = Op2;
347 else if (Op2 == UseOpIdx)
348 NewDstIdx = Op1;
349 else
350 return false;
352 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
353 unsigned NewReg = NewDstMO.getReg();
354 if (NewReg != IntB.reg || !NewDstMO.isKill())
355 return false;
357 // Make sure there are no other definitions of IntB that would reach the
358 // uses which the new definition can reach.
359 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
360 return false;
362 // If some of the uses of IntA.reg is already coalesced away, return false.
363 // It's not possible to determine whether it's safe to perform the coalescing.
364 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
365 UE = mri_->use_end(); UI != UE; ++UI) {
366 MachineInstr *UseMI = &*UI;
367 MachineInstrIndex UseIdx = li_->getInstructionIndex(UseMI);
368 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
369 if (ULR == IntA.end())
370 continue;
371 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
372 return false;
375 // At this point we have decided that it is legal to do this
376 // transformation. Start by commuting the instruction.
377 MachineBasicBlock *MBB = DefMI->getParent();
378 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
379 if (!NewMI)
380 return false;
381 if (NewMI != DefMI) {
382 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
383 MBB->insert(DefMI, NewMI);
384 MBB->erase(DefMI);
386 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
387 NewMI->getOperand(OpIdx).setIsKill();
389 bool BHasPHIKill = BValNo->hasPHIKill();
390 SmallVector<VNInfo*, 4> BDeadValNos;
391 VNInfo::KillSet BKills;
392 std::map<MachineInstrIndex, MachineInstrIndex> BExtend;
394 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
395 // A = or A, B
396 // ...
397 // B = A
398 // ...
399 // C = A<kill>
400 // ...
401 // = B
403 // then do not add kills of A to the newly created B interval.
404 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
405 if (Extended)
406 BExtend[ALR->end] = BLR->end;
408 // Update uses of IntA of the specific Val# with IntB.
409 bool BHasSubRegs = false;
410 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
411 BHasSubRegs = *tri_->getSubRegisters(IntB.reg);
412 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
413 UE = mri_->use_end(); UI != UE;) {
414 MachineOperand &UseMO = UI.getOperand();
415 MachineInstr *UseMI = &*UI;
416 ++UI;
417 if (JoinedCopies.count(UseMI))
418 continue;
419 MachineInstrIndex UseIdx = li_->getInstructionIndex(UseMI);
420 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
421 if (ULR == IntA.end() || ULR->valno != AValNo)
422 continue;
423 UseMO.setReg(NewReg);
424 if (UseMI == CopyMI)
425 continue;
426 if (UseMO.isKill()) {
427 if (Extended)
428 UseMO.setIsKill(false);
429 else
430 BKills.push_back(li_->getNextSlot(li_->getUseIndex(UseIdx)));
432 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
433 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
434 continue;
435 if (DstReg == IntB.reg) {
436 // This copy will become a noop. If it's defining a new val#,
437 // remove that val# as well. However this live range is being
438 // extended to the end of the existing live range defined by the copy.
439 MachineInstrIndex DefIdx = li_->getDefIndex(UseIdx);
440 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
441 BHasPHIKill |= DLR->valno->hasPHIKill();
442 assert(DLR->valno->def == DefIdx);
443 BDeadValNos.push_back(DLR->valno);
444 BExtend[DLR->start] = DLR->end;
445 JoinedCopies.insert(UseMI);
446 // If this is a kill but it's going to be removed, the last use
447 // of the same val# is the new kill.
448 if (UseMO.isKill())
449 BKills.pop_back();
453 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
454 // simply extend BLR if CopyMI doesn't end the range.
455 DEBUG({
456 errs() << "\nExtending: ";
457 IntB.print(errs(), tri_);
460 // Remove val#'s defined by copies that will be coalesced away.
461 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i) {
462 VNInfo *DeadVNI = BDeadValNos[i];
463 if (BHasSubRegs) {
464 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
465 LiveInterval &SRLI = li_->getInterval(*SR);
466 const LiveRange *SRLR = SRLI.getLiveRangeContaining(DeadVNI->def);
467 SRLI.removeValNo(SRLR->valno);
470 IntB.removeValNo(BDeadValNos[i]);
473 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
474 // is updated. Kills are also updated.
475 VNInfo *ValNo = BValNo;
476 ValNo->def = AValNo->def;
477 ValNo->setCopy(0);
478 for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) {
479 if (ValNo->kills[j] != BLR->end)
480 BKills.push_back(ValNo->kills[j]);
482 ValNo->kills.clear();
483 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
484 AI != AE; ++AI) {
485 if (AI->valno != AValNo) continue;
486 MachineInstrIndex End = AI->end;
487 std::map<MachineInstrIndex, MachineInstrIndex>::iterator
488 EI = BExtend.find(End);
489 if (EI != BExtend.end())
490 End = EI->second;
491 IntB.addRange(LiveRange(AI->start, End, ValNo));
493 // If the IntB live range is assigned to a physical register, and if that
494 // physreg has sub-registers, update their live intervals as well.
495 if (BHasSubRegs) {
496 for (const unsigned *SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR) {
497 LiveInterval &SRLI = li_->getInterval(*SR);
498 SRLI.MergeInClobberRange(AI->start, End, li_->getVNInfoAllocator());
502 IntB.addKills(ValNo, BKills);
503 ValNo->setHasPHIKill(BHasPHIKill);
505 DEBUG({
506 errs() << " result = ";
507 IntB.print(errs(), tri_);
508 errs() << '\n';
509 errs() << "\nShortening: ";
510 IntA.print(errs(), tri_);
513 IntA.removeValNo(AValNo);
515 DEBUG({
516 errs() << " result = ";
517 IntA.print(errs(), tri_);
518 errs() << '\n';
521 ++numCommutes;
522 return true;
525 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
526 /// fallthoughs to SuccMBB.
527 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
528 MachineBasicBlock *SuccMBB,
529 const TargetInstrInfo *tii_) {
530 if (MBB == SuccMBB)
531 return true;
532 MachineBasicBlock *TBB = 0, *FBB = 0;
533 SmallVector<MachineOperand, 4> Cond;
534 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
535 MBB->isSuccessor(SuccMBB);
538 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
539 /// from a physical register live interval as well as from the live intervals
540 /// of its sub-registers.
541 static void removeRange(LiveInterval &li,
542 MachineInstrIndex Start, MachineInstrIndex End,
543 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
544 li.removeRange(Start, End, true);
545 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
546 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
547 if (!li_->hasInterval(*SR))
548 continue;
549 LiveInterval &sli = li_->getInterval(*SR);
550 MachineInstrIndex RemoveEnd = Start;
551 while (RemoveEnd != End) {
552 LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
553 if (LR == sli.end())
554 break;
555 RemoveEnd = (LR->end < End) ? LR->end : End;
556 sli.removeRange(Start, RemoveEnd, true);
557 Start = RemoveEnd;
563 /// TrimLiveIntervalToLastUse - If there is a last use in the same basic block
564 /// as the copy instruction, trim the live interval to the last use and return
565 /// true.
566 bool
567 SimpleRegisterCoalescing::TrimLiveIntervalToLastUse(MachineInstrIndex CopyIdx,
568 MachineBasicBlock *CopyMBB,
569 LiveInterval &li,
570 const LiveRange *LR) {
571 MachineInstrIndex MBBStart = li_->getMBBStartIdx(CopyMBB);
572 MachineInstrIndex LastUseIdx;
573 MachineOperand *LastUse =
574 lastRegisterUse(LR->start, li_->getPrevSlot(CopyIdx), li.reg, LastUseIdx);
575 if (LastUse) {
576 MachineInstr *LastUseMI = LastUse->getParent();
577 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
578 // r1024 = op
579 // ...
580 // BB1:
581 // = r1024
583 // BB2:
584 // r1025<dead> = r1024<kill>
585 if (MBBStart < LR->end)
586 removeRange(li, MBBStart, LR->end, li_, tri_);
587 return true;
590 // There are uses before the copy, just shorten the live range to the end
591 // of last use.
592 LastUse->setIsKill();
593 removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
594 LR->valno->addKill(li_->getNextSlot(LastUseIdx));
595 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
596 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
597 DstReg == li.reg) {
598 // Last use is itself an identity code.
599 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
600 LastUseMI->getOperand(DeadIdx).setIsDead();
602 return true;
605 // Is it livein?
606 if (LR->start <= MBBStart && LR->end > MBBStart) {
607 if (LR->start == MachineInstrIndex()) {
608 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
609 // Live-in to the function but dead. Remove it from entry live-in set.
610 mf_->begin()->removeLiveIn(li.reg);
612 // FIXME: Shorten intervals in BBs that reaches this BB.
615 return false;
618 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
619 /// computation, replace the copy by rematerialize the definition.
620 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
621 unsigned DstReg,
622 unsigned DstSubIdx,
623 MachineInstr *CopyMI) {
624 MachineInstrIndex CopyIdx = li_->getUseIndex(li_->getInstructionIndex(CopyMI));
625 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
626 assert(SrcLR != SrcInt.end() && "Live range not found!");
627 VNInfo *ValNo = SrcLR->valno;
628 // If other defs can reach uses of this def, then it's not safe to perform
629 // the optimization. FIXME: Do isPHIDef and isDefAccurate both need to be
630 // tested?
631 if (ValNo->isPHIDef() || !ValNo->isDefAccurate() ||
632 ValNo->isUnused() || ValNo->hasPHIKill())
633 return false;
634 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
635 const TargetInstrDesc &TID = DefMI->getDesc();
636 if (!TID.isAsCheapAsAMove())
637 return false;
638 if (!DefMI->getDesc().isRematerializable() ||
639 !tii_->isTriviallyReMaterializable(DefMI))
640 return false;
641 bool SawStore = false;
642 if (!DefMI->isSafeToMove(tii_, SawStore))
643 return false;
644 if (TID.getNumDefs() != 1)
645 return false;
646 if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF) {
647 // Make sure the copy destination register class fits the instruction
648 // definition register class. The mismatch can happen as a result of earlier
649 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
650 const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(tri_);
651 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
652 if (mri_->getRegClass(DstReg) != RC)
653 return false;
654 } else if (!RC->contains(DstReg))
655 return false;
658 // If destination register has a sub-register index on it, make sure it mtches
659 // the instruction register class.
660 if (DstSubIdx) {
661 const TargetInstrDesc &TID = DefMI->getDesc();
662 if (TID.getNumDefs() != 1)
663 return false;
664 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
665 const TargetRegisterClass *DstSubRC =
666 DstRC->getSubRegisterRegClass(DstSubIdx);
667 const TargetRegisterClass *DefRC = TID.OpInfo[0].getRegClass(tri_);
668 if (DefRC == DstRC)
669 DstSubIdx = 0;
670 else if (DefRC != DstSubRC)
671 return false;
674 MachineInstrIndex DefIdx = li_->getDefIndex(CopyIdx);
675 const LiveRange *DLR= li_->getInterval(DstReg).getLiveRangeContaining(DefIdx);
676 DLR->valno->setCopy(0);
677 // Don't forget to update sub-register intervals.
678 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
679 for (const unsigned* SR = tri_->getSubRegisters(DstReg); *SR; ++SR) {
680 if (!li_->hasInterval(*SR))
681 continue;
682 DLR = li_->getInterval(*SR).getLiveRangeContaining(DefIdx);
683 if (DLR && DLR->valno->getCopy() == CopyMI)
684 DLR->valno->setCopy(0);
688 // If copy kills the source register, find the last use and propagate
689 // kill.
690 bool checkForDeadDef = false;
691 MachineBasicBlock *MBB = CopyMI->getParent();
692 if (CopyMI->killsRegister(SrcInt.reg))
693 if (!TrimLiveIntervalToLastUse(CopyIdx, MBB, SrcInt, SrcLR)) {
694 checkForDeadDef = true;
697 MachineBasicBlock::iterator MII = next(MachineBasicBlock::iterator(CopyMI));
698 tii_->reMaterialize(*MBB, MII, DstReg, DstSubIdx, DefMI);
699 MachineInstr *NewMI = prior(MII);
701 if (checkForDeadDef) {
702 // PR4090 fix: Trim interval failed because there was no use of the
703 // source interval in this MBB. If the def is in this MBB too then we
704 // should mark it dead:
705 if (DefMI->getParent() == MBB) {
706 DefMI->addRegisterDead(SrcInt.reg, tri_);
707 SrcLR->end = li_->getNextSlot(SrcLR->start);
711 // CopyMI may have implicit operands, transfer them over to the newly
712 // rematerialized instruction. And update implicit def interval valnos.
713 for (unsigned i = CopyMI->getDesc().getNumOperands(),
714 e = CopyMI->getNumOperands(); i != e; ++i) {
715 MachineOperand &MO = CopyMI->getOperand(i);
716 if (MO.isReg() && MO.isImplicit())
717 NewMI->addOperand(MO);
718 if (MO.isDef() && li_->hasInterval(MO.getReg())) {
719 unsigned Reg = MO.getReg();
720 DLR = li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
721 if (DLR && DLR->valno->getCopy() == CopyMI)
722 DLR->valno->setCopy(0);
726 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
727 CopyMI->eraseFromParent();
728 ReMatCopies.insert(CopyMI);
729 ReMatDefs.insert(DefMI);
730 ++NumReMats;
731 return true;
734 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
735 /// update the subregister number if it is not zero. If DstReg is a
736 /// physical register and the existing subregister number of the def / use
737 /// being updated is not zero, make sure to set it to the correct physical
738 /// subregister.
739 void
740 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
741 unsigned SubIdx) {
742 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
743 if (DstIsPhys && SubIdx) {
744 // Figure out the real physical register we are updating with.
745 DstReg = tri_->getSubReg(DstReg, SubIdx);
746 SubIdx = 0;
749 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
750 E = mri_->reg_end(); I != E; ) {
751 MachineOperand &O = I.getOperand();
752 MachineInstr *UseMI = &*I;
753 ++I;
754 unsigned OldSubIdx = O.getSubReg();
755 if (DstIsPhys) {
756 unsigned UseDstReg = DstReg;
757 if (OldSubIdx)
758 UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
760 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
761 if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
762 CopySrcSubIdx, CopyDstSubIdx) &&
763 CopySrcReg != CopyDstReg &&
764 CopySrcReg == SrcReg && CopyDstReg != UseDstReg) {
765 // If the use is a copy and it won't be coalesced away, and its source
766 // is defined by a trivial computation, try to rematerialize it instead.
767 if (ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg,
768 CopyDstSubIdx, UseMI))
769 continue;
772 O.setReg(UseDstReg);
773 O.setSubReg(0);
774 continue;
777 // Sub-register indexes goes from small to large. e.g.
778 // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
779 // EAX: 1 -> AL, 2 -> AX
780 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
781 // sub-register 2 is also AX.
782 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
783 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
784 else if (SubIdx)
785 O.setSubReg(SubIdx);
786 // Remove would-be duplicated kill marker.
787 if (O.isKill() && UseMI->killsRegister(DstReg))
788 O.setIsKill(false);
789 O.setReg(DstReg);
791 // After updating the operand, check if the machine instruction has
792 // become a copy. If so, update its val# information.
793 if (JoinedCopies.count(UseMI))
794 continue;
796 const TargetInstrDesc &TID = UseMI->getDesc();
797 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
798 if (TID.getNumDefs() == 1 && TID.getNumOperands() > 2 &&
799 tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
800 CopySrcSubIdx, CopyDstSubIdx) &&
801 CopySrcReg != CopyDstReg &&
802 (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
803 allocatableRegs_[CopyDstReg])) {
804 LiveInterval &LI = li_->getInterval(CopyDstReg);
805 MachineInstrIndex DefIdx =
806 li_->getDefIndex(li_->getInstructionIndex(UseMI));
807 if (const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx)) {
808 if (DLR->valno->def == DefIdx)
809 DLR->valno->setCopy(UseMI);
815 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
816 /// due to live range lengthening as the result of coalescing.
817 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
818 LiveInterval &LI) {
819 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
820 UE = mri_->use_end(); UI != UE; ++UI) {
821 MachineOperand &UseMO = UI.getOperand();
822 if (!UseMO.isKill())
823 continue;
824 MachineInstr *UseMI = UseMO.getParent();
825 MachineInstrIndex UseIdx =
826 li_->getUseIndex(li_->getInstructionIndex(UseMI));
827 const LiveRange *LR = LI.getLiveRangeContaining(UseIdx);
828 if (!LR || !LR->valno->isKill(li_->getNextSlot(UseIdx))) {
829 if (LR->valno->def != li_->getNextSlot(UseIdx)) {
830 // Interesting problem. After coalescing reg1027's def and kill are both
831 // at the same point: %reg1027,0.000000e+00 = [56,814:0) 0@70-(814)
833 // bb5:
834 // 60 %reg1027<def> = t2MOVr %reg1027, 14, %reg0, %reg0
835 // 68 %reg1027<def> = t2LDRi12 %reg1027<kill>, 8, 14, %reg0
836 // 76 t2CMPzri %reg1038<kill,undef>, 0, 14, %reg0, %CPSR<imp-def>
837 // 84 %reg1027<def> = t2MOVr %reg1027, 14, %reg0, %reg0
838 // 96 t2Bcc mbb<bb5,0x2030910>, 1, %CPSR<kill>
840 // Do not remove the kill marker on t2LDRi12.
841 UseMO.setIsKill(false);
847 /// removeIntervalIfEmpty - Check if the live interval of a physical register
848 /// is empty, if so remove it and also remove the empty intervals of its
849 /// sub-registers. Return true if live interval is removed.
850 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
851 const TargetRegisterInfo *tri_) {
852 if (li.empty()) {
853 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
854 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
855 if (!li_->hasInterval(*SR))
856 continue;
857 LiveInterval &sli = li_->getInterval(*SR);
858 if (sli.empty())
859 li_->removeInterval(*SR);
861 li_->removeInterval(li.reg);
862 return true;
864 return false;
867 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
868 /// Return true if live interval is removed.
869 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
870 MachineInstr *CopyMI) {
871 MachineInstrIndex CopyIdx = li_->getInstructionIndex(CopyMI);
872 LiveInterval::iterator MLR =
873 li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
874 if (MLR == li.end())
875 return false; // Already removed by ShortenDeadCopySrcLiveRange.
876 MachineInstrIndex RemoveStart = MLR->start;
877 MachineInstrIndex RemoveEnd = MLR->end;
878 MachineInstrIndex DefIdx = li_->getDefIndex(CopyIdx);
879 // Remove the liverange that's defined by this.
880 if (RemoveStart == DefIdx && RemoveEnd == li_->getNextSlot(DefIdx)) {
881 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
882 return removeIntervalIfEmpty(li, li_, tri_);
884 return false;
887 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
888 /// the val# it defines. If the live interval becomes empty, remove it as well.
889 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
890 MachineInstr *DefMI) {
891 MachineInstrIndex DefIdx = li_->getDefIndex(li_->getInstructionIndex(DefMI));
892 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
893 if (DefIdx != MLR->valno->def)
894 return false;
895 li.removeValNo(MLR->valno);
896 return removeIntervalIfEmpty(li, li_, tri_);
899 /// PropagateDeadness - Propagate the dead marker to the instruction which
900 /// defines the val#.
901 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
902 MachineInstrIndex &LRStart, LiveIntervals *li_,
903 const TargetRegisterInfo* tri_) {
904 MachineInstr *DefMI =
905 li_->getInstructionFromIndex(li_->getDefIndex(LRStart));
906 if (DefMI && DefMI != CopyMI) {
907 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false);
908 if (DeadIdx != -1)
909 DefMI->getOperand(DeadIdx).setIsDead();
910 else
911 DefMI->addOperand(MachineOperand::CreateReg(li.reg,
912 true, true, false, true));
913 LRStart = li_->getNextSlot(LRStart);
917 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
918 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
919 /// ends the live range there. If there isn't another use, then this live range
920 /// is dead. Return true if live interval is removed.
921 bool
922 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
923 MachineInstr *CopyMI) {
924 MachineInstrIndex CopyIdx = li_->getInstructionIndex(CopyMI);
925 if (CopyIdx == MachineInstrIndex()) {
926 // FIXME: special case: function live in. It can be a general case if the
927 // first instruction index starts at > 0 value.
928 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
929 // Live-in to the function but dead. Remove it from entry live-in set.
930 if (mf_->begin()->isLiveIn(li.reg))
931 mf_->begin()->removeLiveIn(li.reg);
932 const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
933 removeRange(li, LR->start, LR->end, li_, tri_);
934 return removeIntervalIfEmpty(li, li_, tri_);
937 LiveInterval::iterator LR =
938 li.FindLiveRangeContaining(li_->getPrevSlot(CopyIdx));
939 if (LR == li.end())
940 // Livein but defined by a phi.
941 return false;
943 MachineInstrIndex RemoveStart = LR->start;
944 MachineInstrIndex RemoveEnd = li_->getNextSlot(li_->getDefIndex(CopyIdx));
945 if (LR->end > RemoveEnd)
946 // More uses past this copy? Nothing to do.
947 return false;
949 // If there is a last use in the same bb, we can't remove the live range.
950 // Shorten the live interval and return.
951 MachineBasicBlock *CopyMBB = CopyMI->getParent();
952 if (TrimLiveIntervalToLastUse(CopyIdx, CopyMBB, li, LR))
953 return false;
955 // There are other kills of the val#. Nothing to do.
956 if (!li.isOnlyLROfValNo(LR))
957 return false;
959 MachineBasicBlock *StartMBB = li_->getMBBFromIndex(RemoveStart);
960 if (!isSameOrFallThroughBB(StartMBB, CopyMBB, tii_))
961 // If the live range starts in another mbb and the copy mbb is not a fall
962 // through mbb, then we can only cut the range from the beginning of the
963 // copy mbb.
964 RemoveStart = li_->getNextSlot(li_->getMBBStartIdx(CopyMBB));
966 if (LR->valno->def == RemoveStart) {
967 // If the def MI defines the val# and this copy is the only kill of the
968 // val#, then propagate the dead marker.
969 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
970 ++numDeadValNo;
972 if (LR->valno->isKill(RemoveEnd))
973 LR->valno->removeKill(RemoveEnd);
976 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
977 return removeIntervalIfEmpty(li, li_, tri_);
980 /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
981 /// from an implicit def to another register can be coalesced away.
982 bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
983 LiveInterval &li,
984 LiveInterval &ImpLi) const{
985 if (!CopyMI->killsRegister(ImpLi.reg))
986 return false;
987 // Make sure this is the only use.
988 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(ImpLi.reg),
989 UE = mri_->use_end(); UI != UE;) {
990 MachineInstr *UseMI = &*UI;
991 ++UI;
992 if (CopyMI == UseMI || JoinedCopies.count(UseMI))
993 continue;
994 return false;
996 return true;
1000 /// isWinToJoinVRWithSrcPhysReg - Return true if it's worth while to join a
1001 /// a virtual destination register with physical source register.
1002 bool
1003 SimpleRegisterCoalescing::isWinToJoinVRWithSrcPhysReg(MachineInstr *CopyMI,
1004 MachineBasicBlock *CopyMBB,
1005 LiveInterval &DstInt,
1006 LiveInterval &SrcInt) {
1007 // If the virtual register live interval is long but it has low use desity,
1008 // do not join them, instead mark the physical register as its allocation
1009 // preference.
1010 const TargetRegisterClass *RC = mri_->getRegClass(DstInt.reg);
1011 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1012 unsigned Length = li_->getApproximateInstructionCount(DstInt);
1013 if (Length > Threshold &&
1014 (((float)std::distance(mri_->use_begin(DstInt.reg),
1015 mri_->use_end()) / Length) < (1.0 / Threshold)))
1016 return false;
1018 // If the virtual register live interval extends into a loop, turn down
1019 // aggressiveness.
1020 MachineInstrIndex CopyIdx =
1021 li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1022 const MachineLoop *L = loopInfo->getLoopFor(CopyMBB);
1023 if (!L) {
1024 // Let's see if the virtual register live interval extends into the loop.
1025 LiveInterval::iterator DLR = DstInt.FindLiveRangeContaining(CopyIdx);
1026 assert(DLR != DstInt.end() && "Live range not found!");
1027 DLR = DstInt.FindLiveRangeContaining(li_->getNextSlot(DLR->end));
1028 if (DLR != DstInt.end()) {
1029 CopyMBB = li_->getMBBFromIndex(DLR->start);
1030 L = loopInfo->getLoopFor(CopyMBB);
1034 if (!L || Length <= Threshold)
1035 return true;
1037 MachineInstrIndex UseIdx = li_->getUseIndex(CopyIdx);
1038 LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1039 MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1040 if (loopInfo->getLoopFor(SMBB) != L) {
1041 if (!loopInfo->isLoopHeader(CopyMBB))
1042 return false;
1043 // If vr's live interval extends pass the loop header, do not join.
1044 for (MachineBasicBlock::succ_iterator SI = CopyMBB->succ_begin(),
1045 SE = CopyMBB->succ_end(); SI != SE; ++SI) {
1046 MachineBasicBlock *SuccMBB = *SI;
1047 if (SuccMBB == CopyMBB)
1048 continue;
1049 if (DstInt.overlaps(li_->getMBBStartIdx(SuccMBB),
1050 li_->getNextSlot(li_->getMBBEndIdx(SuccMBB))))
1051 return false;
1054 return true;
1057 /// isWinToJoinVRWithDstPhysReg - Return true if it's worth while to join a
1058 /// copy from a virtual source register to a physical destination register.
1059 bool
1060 SimpleRegisterCoalescing::isWinToJoinVRWithDstPhysReg(MachineInstr *CopyMI,
1061 MachineBasicBlock *CopyMBB,
1062 LiveInterval &DstInt,
1063 LiveInterval &SrcInt) {
1064 // If the virtual register live interval is long but it has low use desity,
1065 // do not join them, instead mark the physical register as its allocation
1066 // preference.
1067 const TargetRegisterClass *RC = mri_->getRegClass(SrcInt.reg);
1068 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1069 unsigned Length = li_->getApproximateInstructionCount(SrcInt);
1070 if (Length > Threshold &&
1071 (((float)std::distance(mri_->use_begin(SrcInt.reg),
1072 mri_->use_end()) / Length) < (1.0 / Threshold)))
1073 return false;
1075 if (SrcInt.empty())
1076 // Must be implicit_def.
1077 return false;
1079 // If the virtual register live interval is defined or cross a loop, turn
1080 // down aggressiveness.
1081 MachineInstrIndex CopyIdx =
1082 li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1083 MachineInstrIndex UseIdx = li_->getUseIndex(CopyIdx);
1084 LiveInterval::iterator SLR = SrcInt.FindLiveRangeContaining(UseIdx);
1085 assert(SLR != SrcInt.end() && "Live range not found!");
1086 SLR = SrcInt.FindLiveRangeContaining(li_->getPrevSlot(SLR->start));
1087 if (SLR == SrcInt.end())
1088 return true;
1089 MachineBasicBlock *SMBB = li_->getMBBFromIndex(SLR->start);
1090 const MachineLoop *L = loopInfo->getLoopFor(SMBB);
1092 if (!L || Length <= Threshold)
1093 return true;
1095 if (loopInfo->getLoopFor(CopyMBB) != L) {
1096 if (SMBB != L->getLoopLatch())
1097 return false;
1098 // If vr's live interval is extended from before the loop latch, do not
1099 // join.
1100 for (MachineBasicBlock::pred_iterator PI = SMBB->pred_begin(),
1101 PE = SMBB->pred_end(); PI != PE; ++PI) {
1102 MachineBasicBlock *PredMBB = *PI;
1103 if (PredMBB == SMBB)
1104 continue;
1105 if (SrcInt.overlaps(li_->getMBBStartIdx(PredMBB),
1106 li_->getNextSlot(li_->getMBBEndIdx(PredMBB))))
1107 return false;
1110 return true;
1113 /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
1114 /// two virtual registers from different register classes.
1115 bool
1116 SimpleRegisterCoalescing::isWinToJoinCrossClass(unsigned LargeReg,
1117 unsigned SmallReg,
1118 unsigned Threshold) {
1119 // Then make sure the intervals are *short*.
1120 LiveInterval &LargeInt = li_->getInterval(LargeReg);
1121 LiveInterval &SmallInt = li_->getInterval(SmallReg);
1122 unsigned LargeSize = li_->getApproximateInstructionCount(LargeInt);
1123 unsigned SmallSize = li_->getApproximateInstructionCount(SmallInt);
1124 if (SmallSize > Threshold || LargeSize > Threshold)
1125 if ((float)std::distance(mri_->use_begin(SmallReg),
1126 mri_->use_end()) / SmallSize <
1127 (float)std::distance(mri_->use_begin(LargeReg),
1128 mri_->use_end()) / LargeSize)
1129 return false;
1130 return true;
1133 /// HasIncompatibleSubRegDefUse - If we are trying to coalesce a virtual
1134 /// register with a physical register, check if any of the virtual register
1135 /// operand is a sub-register use or def. If so, make sure it won't result
1136 /// in an illegal extract_subreg or insert_subreg instruction. e.g.
1137 /// vr1024 = extract_subreg vr1025, 1
1138 /// ...
1139 /// vr1024 = mov8rr AH
1140 /// If vr1024 is coalesced with AH, the extract_subreg is now illegal since
1141 /// AH does not have a super-reg whose sub-register 1 is AH.
1142 bool
1143 SimpleRegisterCoalescing::HasIncompatibleSubRegDefUse(MachineInstr *CopyMI,
1144 unsigned VirtReg,
1145 unsigned PhysReg) {
1146 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(VirtReg),
1147 E = mri_->reg_end(); I != E; ++I) {
1148 MachineOperand &O = I.getOperand();
1149 MachineInstr *MI = &*I;
1150 if (MI == CopyMI || JoinedCopies.count(MI))
1151 continue;
1152 unsigned SubIdx = O.getSubReg();
1153 if (SubIdx && !tri_->getSubReg(PhysReg, SubIdx))
1154 return true;
1155 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1156 SubIdx = MI->getOperand(2).getImm();
1157 if (O.isUse() && !tri_->getSubReg(PhysReg, SubIdx))
1158 return true;
1159 if (O.isDef()) {
1160 unsigned SrcReg = MI->getOperand(1).getReg();
1161 const TargetRegisterClass *RC =
1162 TargetRegisterInfo::isPhysicalRegister(SrcReg)
1163 ? tri_->getPhysicalRegisterRegClass(SrcReg)
1164 : mri_->getRegClass(SrcReg);
1165 if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
1166 return true;
1169 if (MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
1170 MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
1171 SubIdx = MI->getOperand(3).getImm();
1172 if (VirtReg == MI->getOperand(0).getReg()) {
1173 if (!tri_->getSubReg(PhysReg, SubIdx))
1174 return true;
1175 } else {
1176 unsigned DstReg = MI->getOperand(0).getReg();
1177 const TargetRegisterClass *RC =
1178 TargetRegisterInfo::isPhysicalRegister(DstReg)
1179 ? tri_->getPhysicalRegisterRegClass(DstReg)
1180 : mri_->getRegClass(DstReg);
1181 if (!tri_->getMatchingSuperReg(PhysReg, SubIdx, RC))
1182 return true;
1186 return false;
1190 /// CanJoinExtractSubRegToPhysReg - Return true if it's possible to coalesce
1191 /// an extract_subreg where dst is a physical register, e.g.
1192 /// cl = EXTRACT_SUBREG reg1024, 1
1193 bool
1194 SimpleRegisterCoalescing::CanJoinExtractSubRegToPhysReg(unsigned DstReg,
1195 unsigned SrcReg, unsigned SubIdx,
1196 unsigned &RealDstReg) {
1197 const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
1198 RealDstReg = tri_->getMatchingSuperReg(DstReg, SubIdx, RC);
1199 assert(RealDstReg && "Invalid extract_subreg instruction!");
1201 // For this type of EXTRACT_SUBREG, conservatively
1202 // check if the live interval of the source register interfere with the
1203 // actual super physical register we are trying to coalesce with.
1204 LiveInterval &RHS = li_->getInterval(SrcReg);
1205 if (li_->hasInterval(RealDstReg) &&
1206 RHS.overlaps(li_->getInterval(RealDstReg))) {
1207 DEBUG({
1208 errs() << "Interfere with register ";
1209 li_->getInterval(RealDstReg).print(errs(), tri_);
1211 return false; // Not coalescable
1213 for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
1214 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1215 DEBUG({
1216 errs() << "Interfere with sub-register ";
1217 li_->getInterval(*SR).print(errs(), tri_);
1219 return false; // Not coalescable
1221 return true;
1224 /// CanJoinInsertSubRegToPhysReg - Return true if it's possible to coalesce
1225 /// an insert_subreg where src is a physical register, e.g.
1226 /// reg1024 = INSERT_SUBREG reg1024, c1, 0
1227 bool
1228 SimpleRegisterCoalescing::CanJoinInsertSubRegToPhysReg(unsigned DstReg,
1229 unsigned SrcReg, unsigned SubIdx,
1230 unsigned &RealSrcReg) {
1231 const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
1232 RealSrcReg = tri_->getMatchingSuperReg(SrcReg, SubIdx, RC);
1233 assert(RealSrcReg && "Invalid extract_subreg instruction!");
1235 LiveInterval &RHS = li_->getInterval(DstReg);
1236 if (li_->hasInterval(RealSrcReg) &&
1237 RHS.overlaps(li_->getInterval(RealSrcReg))) {
1238 DEBUG({
1239 errs() << "Interfere with register ";
1240 li_->getInterval(RealSrcReg).print(errs(), tri_);
1242 return false; // Not coalescable
1244 for (const unsigned* SR = tri_->getSubRegisters(RealSrcReg); *SR; ++SR)
1245 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1246 DEBUG({
1247 errs() << "Interfere with sub-register ";
1248 li_->getInterval(*SR).print(errs(), tri_);
1250 return false; // Not coalescable
1252 return true;
1255 /// getRegAllocPreference - Return register allocation preference register.
1257 static unsigned getRegAllocPreference(unsigned Reg, MachineFunction &MF,
1258 MachineRegisterInfo *MRI,
1259 const TargetRegisterInfo *TRI) {
1260 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1261 return 0;
1262 std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
1263 return TRI->ResolveRegAllocHint(Hint.first, Hint.second, MF);
1266 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1267 /// which are the src/dst of the copy instruction CopyMI. This returns true
1268 /// if the copy was successfully coalesced away. If it is not currently
1269 /// possible to coalesce this interval, but it may be possible if other
1270 /// things get coalesced, then it returns true by reference in 'Again'.
1271 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1272 MachineInstr *CopyMI = TheCopy.MI;
1274 Again = false;
1275 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1276 return false; // Already done.
1278 DEBUG(errs() << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1280 unsigned SrcReg, DstReg, SrcSubIdx = 0, DstSubIdx = 0;
1281 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
1282 bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG;
1283 bool isSubRegToReg = CopyMI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG;
1284 unsigned SubIdx = 0;
1285 if (isExtSubReg) {
1286 DstReg = CopyMI->getOperand(0).getReg();
1287 DstSubIdx = CopyMI->getOperand(0).getSubReg();
1288 SrcReg = CopyMI->getOperand(1).getReg();
1289 SrcSubIdx = CopyMI->getOperand(2).getImm();
1290 } else if (isInsSubReg || isSubRegToReg) {
1291 DstReg = CopyMI->getOperand(0).getReg();
1292 DstSubIdx = CopyMI->getOperand(3).getImm();
1293 SrcReg = CopyMI->getOperand(2).getReg();
1294 SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1295 if (SrcSubIdx && SrcSubIdx != DstSubIdx) {
1296 // r1025 = INSERT_SUBREG r1025, r1024<2>, 2 Then r1024 has already been
1297 // coalesced to a larger register so the subreg indices cancel out.
1298 DEBUG(errs() << "\tSource of insert_subreg is already coalesced "
1299 << "to another register.\n");
1300 return false; // Not coalescable.
1302 } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)){
1303 llvm_unreachable("Unrecognized copy instruction!");
1306 // If they are already joined we continue.
1307 if (SrcReg == DstReg) {
1308 DEBUG(errs() << "\tCopy already coalesced.\n");
1309 return false; // Not coalescable.
1312 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1313 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1315 // If they are both physical registers, we cannot join them.
1316 if (SrcIsPhys && DstIsPhys) {
1317 DEBUG(errs() << "\tCan not coalesce physregs.\n");
1318 return false; // Not coalescable.
1321 // We only join virtual registers with allocatable physical registers.
1322 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
1323 DEBUG(errs() << "\tSrc reg is unallocatable physreg.\n");
1324 return false; // Not coalescable.
1326 if (DstIsPhys && !allocatableRegs_[DstReg]) {
1327 DEBUG(errs() << "\tDst reg is unallocatable physreg.\n");
1328 return false; // Not coalescable.
1331 // Check that a physical source register is compatible with dst regclass
1332 if (SrcIsPhys) {
1333 unsigned SrcSubReg = SrcSubIdx ?
1334 tri_->getSubReg(SrcReg, SrcSubIdx) : SrcReg;
1335 const TargetRegisterClass *DstRC = mri_->getRegClass(DstReg);
1336 const TargetRegisterClass *DstSubRC = DstRC;
1337 if (DstSubIdx)
1338 DstSubRC = DstRC->getSubRegisterRegClass(DstSubIdx);
1339 assert(DstSubRC && "Illegal subregister index");
1340 if (!DstSubRC->contains(SrcSubReg)) {
1341 DEBUG(errs() << "\tIncompatible destination regclass: "
1342 << tri_->getName(SrcSubReg) << " not in "
1343 << DstSubRC->getName() << ".\n");
1344 return false; // Not coalescable.
1348 // Check that a physical dst register is compatible with source regclass
1349 if (DstIsPhys) {
1350 unsigned DstSubReg = DstSubIdx ?
1351 tri_->getSubReg(DstReg, DstSubIdx) : DstReg;
1352 const TargetRegisterClass *SrcRC = mri_->getRegClass(SrcReg);
1353 const TargetRegisterClass *SrcSubRC = SrcRC;
1354 if (SrcSubIdx)
1355 SrcSubRC = SrcRC->getSubRegisterRegClass(SrcSubIdx);
1356 assert(SrcSubRC && "Illegal subregister index");
1357 if (!SrcSubRC->contains(DstReg)) {
1358 DEBUG(errs() << "\tIncompatible source regclass: "
1359 << tri_->getName(DstSubReg) << " not in "
1360 << SrcSubRC->getName() << ".\n");
1361 (void)DstSubReg;
1362 return false; // Not coalescable.
1366 // Should be non-null only when coalescing to a sub-register class.
1367 bool CrossRC = false;
1368 const TargetRegisterClass *SrcRC= SrcIsPhys ? 0 : mri_->getRegClass(SrcReg);
1369 const TargetRegisterClass *DstRC= DstIsPhys ? 0 : mri_->getRegClass(DstReg);
1370 const TargetRegisterClass *NewRC = NULL;
1371 MachineBasicBlock *CopyMBB = CopyMI->getParent();
1372 unsigned RealDstReg = 0;
1373 unsigned RealSrcReg = 0;
1374 if (isExtSubReg || isInsSubReg || isSubRegToReg) {
1375 SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
1376 if (SrcIsPhys && isExtSubReg) {
1377 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
1378 // coalesced with AX.
1379 unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
1380 if (DstSubIdx) {
1381 // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
1382 // coalesced to a larger register so the subreg indices cancel out.
1383 if (DstSubIdx != SubIdx) {
1384 DEBUG(errs() << "\t Sub-register indices mismatch.\n");
1385 return false; // Not coalescable.
1387 } else
1388 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
1389 SubIdx = 0;
1390 } else if (DstIsPhys && (isInsSubReg || isSubRegToReg)) {
1391 // EAX = INSERT_SUBREG EAX, r1024, 0
1392 unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1393 if (SrcSubIdx) {
1394 // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
1395 // coalesced to a larger register so the subreg indices cancel out.
1396 if (SrcSubIdx != SubIdx) {
1397 DEBUG(errs() << "\t Sub-register indices mismatch.\n");
1398 return false; // Not coalescable.
1400 } else
1401 DstReg = tri_->getSubReg(DstReg, SubIdx);
1402 SubIdx = 0;
1403 } else if ((DstIsPhys && isExtSubReg) ||
1404 (SrcIsPhys && (isInsSubReg || isSubRegToReg))) {
1405 if (!isSubRegToReg && CopyMI->getOperand(1).getSubReg()) {
1406 DEBUG(errs() << "\tSrc of extract_subreg already coalesced with reg"
1407 << " of a super-class.\n");
1408 return false; // Not coalescable.
1411 if (isExtSubReg) {
1412 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealDstReg))
1413 return false; // Not coalescable
1414 } else {
1415 if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1416 return false; // Not coalescable
1418 SubIdx = 0;
1419 } else {
1420 unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
1421 : CopyMI->getOperand(2).getSubReg();
1422 if (OldSubIdx) {
1423 if (OldSubIdx == SubIdx && !differingRegisterClasses(SrcReg, DstReg))
1424 // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
1425 // coalesced to a larger register so the subreg indices cancel out.
1426 // Also check if the other larger register is of the same register
1427 // class as the would be resulting register.
1428 SubIdx = 0;
1429 else {
1430 DEBUG(errs() << "\t Sub-register indices mismatch.\n");
1431 return false; // Not coalescable.
1434 if (SubIdx) {
1435 if (!DstIsPhys && !SrcIsPhys) {
1436 if (isInsSubReg || isSubRegToReg) {
1437 NewRC = tri_->getMatchingSuperRegClass(DstRC, SrcRC, SubIdx);
1438 } else // extract_subreg {
1439 NewRC = tri_->getMatchingSuperRegClass(SrcRC, DstRC, SubIdx);
1441 if (!NewRC) {
1442 DEBUG(errs() << "\t Conflicting sub-register indices.\n");
1443 return false; // Not coalescable
1446 unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
1447 unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
1448 unsigned Limit= allocatableRCRegs_[mri_->getRegClass(SmallReg)].count();
1449 if (!isWinToJoinCrossClass(LargeReg, SmallReg, Limit)) {
1450 Again = true; // May be possible to coalesce later.
1451 return false;
1455 } else if (differingRegisterClasses(SrcReg, DstReg)) {
1456 if (DisableCrossClassJoin)
1457 return false;
1458 CrossRC = true;
1460 // FIXME: What if the result of a EXTRACT_SUBREG is then coalesced
1461 // with another? If it's the resulting destination register, then
1462 // the subidx must be propagated to uses (but only those defined
1463 // by the EXTRACT_SUBREG). If it's being coalesced into another
1464 // register, it should be safe because register is assumed to have
1465 // the register class of the super-register.
1467 // Process moves where one of the registers have a sub-register index.
1468 MachineOperand *DstMO = CopyMI->findRegisterDefOperand(DstReg);
1469 MachineOperand *SrcMO = CopyMI->findRegisterUseOperand(SrcReg);
1470 SubIdx = DstMO->getSubReg();
1471 if (SubIdx) {
1472 if (SrcMO->getSubReg())
1473 // FIXME: can we handle this?
1474 return false;
1475 // This is not an insert_subreg but it looks like one.
1476 // e.g. %reg1024:4 = MOV32rr %EAX
1477 isInsSubReg = true;
1478 if (SrcIsPhys) {
1479 if (!CanJoinInsertSubRegToPhysReg(DstReg, SrcReg, SubIdx, RealSrcReg))
1480 return false; // Not coalescable
1481 SubIdx = 0;
1483 } else {
1484 SubIdx = SrcMO->getSubReg();
1485 if (SubIdx) {
1486 // This is not a extract_subreg but it looks like one.
1487 // e.g. %cl = MOV16rr %reg1024:1
1488 isExtSubReg = true;
1489 if (DstIsPhys) {
1490 if (!CanJoinExtractSubRegToPhysReg(DstReg, SrcReg, SubIdx,RealDstReg))
1491 return false; // Not coalescable
1492 SubIdx = 0;
1497 unsigned LargeReg = SrcReg;
1498 unsigned SmallReg = DstReg;
1500 // Now determine the register class of the joined register.
1501 if (isExtSubReg) {
1502 if (SubIdx && DstRC && DstRC->isASubClass()) {
1503 // This is a move to a sub-register class. However, the source is a
1504 // sub-register of a larger register class. We don't know what should
1505 // the register class be. FIXME.
1506 Again = true;
1507 return false;
1509 if (!DstIsPhys && !SrcIsPhys)
1510 NewRC = SrcRC;
1511 } else if (!SrcIsPhys && !DstIsPhys) {
1512 NewRC = getCommonSubClass(SrcRC, DstRC);
1513 if (!NewRC) {
1514 DEBUG(errs() << "\tDisjoint regclasses: "
1515 << SrcRC->getName() << ", "
1516 << DstRC->getName() << ".\n");
1517 return false; // Not coalescable.
1519 if (DstRC->getSize() > SrcRC->getSize())
1520 std::swap(LargeReg, SmallReg);
1523 // If we are joining two virtual registers and the resulting register
1524 // class is more restrictive (fewer register, smaller size). Check if it's
1525 // worth doing the merge.
1526 if (!SrcIsPhys && !DstIsPhys &&
1527 (isExtSubReg || DstRC->isASubClass()) &&
1528 !isWinToJoinCrossClass(LargeReg, SmallReg,
1529 allocatableRCRegs_[NewRC].count())) {
1530 DEBUG(errs() << "\tSrc/Dest are different register classes.\n");
1531 // Allow the coalescer to try again in case either side gets coalesced to
1532 // a physical register that's compatible with the other side. e.g.
1533 // r1024 = MOV32to32_ r1025
1534 // But later r1024 is assigned EAX then r1025 may be coalesced with EAX.
1535 Again = true; // May be possible to coalesce later.
1536 return false;
1540 // Will it create illegal extract_subreg / insert_subreg?
1541 if (SrcIsPhys && HasIncompatibleSubRegDefUse(CopyMI, DstReg, SrcReg))
1542 return false;
1543 if (DstIsPhys && HasIncompatibleSubRegDefUse(CopyMI, SrcReg, DstReg))
1544 return false;
1546 LiveInterval &SrcInt = li_->getInterval(SrcReg);
1547 LiveInterval &DstInt = li_->getInterval(DstReg);
1548 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
1549 "Register mapping is horribly broken!");
1551 DEBUG({
1552 errs() << "\t\tInspecting "; SrcInt.print(errs(), tri_);
1553 errs() << " and "; DstInt.print(errs(), tri_);
1554 errs() << ": ";
1557 // Save a copy of the virtual register live interval. We'll manually
1558 // merge this into the "real" physical register live interval this is
1559 // coalesced with.
1560 LiveInterval *SavedLI = 0;
1561 if (RealDstReg)
1562 SavedLI = li_->dupInterval(&SrcInt);
1563 else if (RealSrcReg)
1564 SavedLI = li_->dupInterval(&DstInt);
1566 // Check if it is necessary to propagate "isDead" property.
1567 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg) {
1568 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1569 bool isDead = mopd->isDead();
1571 // We need to be careful about coalescing a source physical register with a
1572 // virtual register. Once the coalescing is done, it cannot be broken and
1573 // these are not spillable! If the destination interval uses are far away,
1574 // think twice about coalescing them!
1575 if (!isDead && (SrcIsPhys || DstIsPhys)) {
1576 // If the copy is in a loop, take care not to coalesce aggressively if the
1577 // src is coming in from outside the loop (or the dst is out of the loop).
1578 // If it's not in a loop, then determine whether to join them base purely
1579 // by the length of the interval.
1580 if (PhysJoinTweak) {
1581 if (SrcIsPhys) {
1582 if (!isWinToJoinVRWithSrcPhysReg(CopyMI, CopyMBB, DstInt, SrcInt)) {
1583 mri_->setRegAllocationHint(DstInt.reg, 0, SrcReg);
1584 ++numAborts;
1585 DEBUG(errs() << "\tMay tie down a physical register, abort!\n");
1586 Again = true; // May be possible to coalesce later.
1587 return false;
1589 } else {
1590 if (!isWinToJoinVRWithDstPhysReg(CopyMI, CopyMBB, DstInt, SrcInt)) {
1591 mri_->setRegAllocationHint(SrcInt.reg, 0, DstReg);
1592 ++numAborts;
1593 DEBUG(errs() << "\tMay tie down a physical register, abort!\n");
1594 Again = true; // May be possible to coalesce later.
1595 return false;
1598 } else {
1599 // If the virtual register live interval is long but it has low use desity,
1600 // do not join them, instead mark the physical register as its allocation
1601 // preference.
1602 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1603 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1604 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1605 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1606 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1607 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1608 float Ratio = 1.0 / Threshold;
1609 if (Length > Threshold &&
1610 (((float)std::distance(mri_->use_begin(JoinVReg),
1611 mri_->use_end()) / Length) < Ratio)) {
1612 mri_->setRegAllocationHint(JoinVInt.reg, 0, JoinPReg);
1613 ++numAborts;
1614 DEBUG(errs() << "\tMay tie down a physical register, abort!\n");
1615 Again = true; // May be possible to coalesce later.
1616 return false;
1622 // Okay, attempt to join these two intervals. On failure, this returns false.
1623 // Otherwise, if one of the intervals being joined is a physreg, this method
1624 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1625 // been modified, so we can use this information below to update aliases.
1626 bool Swapped = false;
1627 // If SrcInt is implicitly defined, it's safe to coalesce.
1628 bool isEmpty = SrcInt.empty();
1629 if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
1630 // Only coalesce an empty interval (defined by implicit_def) with
1631 // another interval which has a valno defined by the CopyMI and the CopyMI
1632 // is a kill of the implicit def.
1633 DEBUG(errs() << "Not profitable!\n");
1634 return false;
1637 if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
1638 // Coalescing failed.
1640 // If definition of source is defined by trivial computation, try
1641 // rematerializing it.
1642 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
1643 ReMaterializeTrivialDef(SrcInt, DstReg, DstSubIdx, CopyMI))
1644 return true;
1646 // If we can eliminate the copy without merging the live ranges, do so now.
1647 if (!isExtSubReg && !isInsSubReg && !isSubRegToReg &&
1648 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1649 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
1650 JoinedCopies.insert(CopyMI);
1651 return true;
1654 // Otherwise, we are unable to join the intervals.
1655 DEBUG(errs() << "Interference!\n");
1656 Again = true; // May be possible to coalesce later.
1657 return false;
1660 LiveInterval *ResSrcInt = &SrcInt;
1661 LiveInterval *ResDstInt = &DstInt;
1662 if (Swapped) {
1663 std::swap(SrcReg, DstReg);
1664 std::swap(ResSrcInt, ResDstInt);
1666 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1667 "LiveInterval::join didn't work right!");
1669 // If we're about to merge live ranges into a physical register live interval,
1670 // we have to update any aliased register's live ranges to indicate that they
1671 // have clobbered values for this range.
1672 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1673 // If this is a extract_subreg where dst is a physical register, e.g.
1674 // cl = EXTRACT_SUBREG reg1024, 1
1675 // then create and update the actual physical register allocated to RHS.
1676 if (RealDstReg || RealSrcReg) {
1677 LiveInterval &RealInt =
1678 li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
1679 for (LiveInterval::const_vni_iterator I = SavedLI->vni_begin(),
1680 E = SavedLI->vni_end(); I != E; ++I) {
1681 const VNInfo *ValNo = *I;
1682 VNInfo *NewValNo = RealInt.getNextValue(ValNo->def, ValNo->getCopy(),
1683 false, // updated at *
1684 li_->getVNInfoAllocator());
1685 NewValNo->setFlags(ValNo->getFlags()); // * updated here.
1686 RealInt.addKills(NewValNo, ValNo->kills);
1687 RealInt.MergeValueInAsValue(*SavedLI, ValNo, NewValNo);
1689 RealInt.weight += SavedLI->weight;
1690 DstReg = RealDstReg ? RealDstReg : RealSrcReg;
1693 // Update the liveintervals of sub-registers.
1694 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
1695 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
1696 li_->getVNInfoAllocator());
1699 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1700 // larger super-register.
1701 if ((isExtSubReg || isInsSubReg || isSubRegToReg) &&
1702 !SrcIsPhys && !DstIsPhys) {
1703 if ((isExtSubReg && !Swapped) ||
1704 ((isInsSubReg || isSubRegToReg) && Swapped)) {
1705 ResSrcInt->Copy(*ResDstInt, mri_, li_->getVNInfoAllocator());
1706 std::swap(SrcReg, DstReg);
1707 std::swap(ResSrcInt, ResDstInt);
1711 // Coalescing to a virtual register that is of a sub-register class of the
1712 // other. Make sure the resulting register is set to the right register class.
1713 if (CrossRC)
1714 ++numCrossRCs;
1716 // This may happen even if it's cross-rc coalescing. e.g.
1717 // %reg1026<def> = SUBREG_TO_REG 0, %reg1037<kill>, 4
1718 // reg1026 -> GR64, reg1037 -> GR32_ABCD. The resulting register will have to
1719 // be allocate a register from GR64_ABCD.
1720 if (NewRC)
1721 mri_->setRegClass(DstReg, NewRC);
1723 // Remember to delete the copy instruction.
1724 JoinedCopies.insert(CopyMI);
1726 // Some live range has been lengthened due to colaescing, eliminate the
1727 // unnecessary kills.
1728 RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1729 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1730 RemoveUnnecessaryKills(DstReg, *ResDstInt);
1732 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1734 // SrcReg is guarateed to be the register whose live interval that is
1735 // being merged.
1736 li_->removeInterval(SrcReg);
1738 // Update regalloc hint.
1739 tri_->UpdateRegAllocHint(SrcReg, DstReg, *mf_);
1741 // Manually deleted the live interval copy.
1742 if (SavedLI) {
1743 SavedLI->clear();
1744 delete SavedLI;
1747 // If resulting interval has a preference that no longer fits because of subreg
1748 // coalescing, just clear the preference.
1749 unsigned Preference = getRegAllocPreference(ResDstInt->reg, *mf_, mri_, tri_);
1750 if (Preference && (isExtSubReg || isInsSubReg || isSubRegToReg) &&
1751 TargetRegisterInfo::isVirtualRegister(ResDstInt->reg)) {
1752 const TargetRegisterClass *RC = mri_->getRegClass(ResDstInt->reg);
1753 if (!RC->contains(Preference))
1754 mri_->setRegAllocationHint(ResDstInt->reg, 0, 0);
1757 DEBUG({
1758 errs() << "\n\t\tJoined. Result = ";
1759 ResDstInt->print(errs(), tri_);
1760 errs() << "\n";
1763 ++numJoins;
1764 return true;
1767 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1768 /// compute what the resultant value numbers for each value in the input two
1769 /// ranges will be. This is complicated by copies between the two which can
1770 /// and will commonly cause multiple value numbers to be merged into one.
1772 /// VN is the value number that we're trying to resolve. InstDefiningValue
1773 /// keeps track of the new InstDefiningValue assignment for the result
1774 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1775 /// whether a value in this or other is a copy from the opposite set.
1776 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1777 /// already been assigned.
1779 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1780 /// contains the value number the copy is from.
1782 static unsigned ComputeUltimateVN(VNInfo *VNI,
1783 SmallVector<VNInfo*, 16> &NewVNInfo,
1784 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1785 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1786 SmallVector<int, 16> &ThisValNoAssignments,
1787 SmallVector<int, 16> &OtherValNoAssignments) {
1788 unsigned VN = VNI->id;
1790 // If the VN has already been computed, just return it.
1791 if (ThisValNoAssignments[VN] >= 0)
1792 return ThisValNoAssignments[VN];
1793 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
1795 // If this val is not a copy from the other val, then it must be a new value
1796 // number in the destination.
1797 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1798 if (I == ThisFromOther.end()) {
1799 NewVNInfo.push_back(VNI);
1800 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1802 VNInfo *OtherValNo = I->second;
1804 // Otherwise, this *is* a copy from the RHS. If the other side has already
1805 // been computed, return it.
1806 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1807 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1809 // Mark this value number as currently being computed, then ask what the
1810 // ultimate value # of the other value is.
1811 ThisValNoAssignments[VN] = -2;
1812 unsigned UltimateVN =
1813 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1814 OtherValNoAssignments, ThisValNoAssignments);
1815 return ThisValNoAssignments[VN] = UltimateVN;
1818 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
1819 return std::find(V.begin(), V.end(), Val) != V.end();
1822 /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1823 /// the specified live interval is defined by a copy from the specified
1824 /// register.
1825 bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1826 LiveRange *LR,
1827 unsigned Reg) {
1828 unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1829 if (SrcReg == Reg)
1830 return true;
1831 // FIXME: Do isPHIDef and isDefAccurate both need to be tested?
1832 if ((LR->valno->isPHIDef() || !LR->valno->isDefAccurate()) &&
1833 TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1834 *tri_->getSuperRegisters(li.reg)) {
1835 // It's a sub-register live interval, we may not have precise information.
1836 // Re-compute it.
1837 MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1838 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1839 if (DefMI &&
1840 tii_->isMoveInstr(*DefMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
1841 DstReg == li.reg && SrcReg == Reg) {
1842 // Cache computed info.
1843 LR->valno->def = LR->start;
1844 LR->valno->setCopy(DefMI);
1845 return true;
1848 return false;
1851 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1852 /// caller of this method must guarantee that the RHS only contains a single
1853 /// value number and that the RHS is not defined by a copy from this
1854 /// interval. This returns false if the intervals are not joinable, or it
1855 /// joins them and returns true.
1856 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
1857 assert(RHS.containsOneValue());
1859 // Some number (potentially more than one) value numbers in the current
1860 // interval may be defined as copies from the RHS. Scan the overlapping
1861 // portions of the LHS and RHS, keeping track of this and looking for
1862 // overlapping live ranges that are NOT defined as copies. If these exist, we
1863 // cannot coalesce.
1865 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1866 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1868 if (LHSIt->start < RHSIt->start) {
1869 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1870 if (LHSIt != LHS.begin()) --LHSIt;
1871 } else if (RHSIt->start < LHSIt->start) {
1872 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1873 if (RHSIt != RHS.begin()) --RHSIt;
1876 SmallVector<VNInfo*, 8> EliminatedLHSVals;
1878 while (1) {
1879 // Determine if these live intervals overlap.
1880 bool Overlaps = false;
1881 if (LHSIt->start <= RHSIt->start)
1882 Overlaps = LHSIt->end > RHSIt->start;
1883 else
1884 Overlaps = RHSIt->end > LHSIt->start;
1886 // If the live intervals overlap, there are two interesting cases: if the
1887 // LHS interval is defined by a copy from the RHS, it's ok and we record
1888 // that the LHS value # is the same as the RHS. If it's not, then we cannot
1889 // coalesce these live ranges and we bail out.
1890 if (Overlaps) {
1891 // If we haven't already recorded that this value # is safe, check it.
1892 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
1893 // Copy from the RHS?
1894 if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
1895 return false; // Nope, bail out.
1897 if (LHSIt->contains(RHSIt->valno->def))
1898 // Here is an interesting situation:
1899 // BB1:
1900 // vr1025 = copy vr1024
1901 // ..
1902 // BB2:
1903 // vr1024 = op
1904 // = vr1025
1905 // Even though vr1025 is copied from vr1024, it's not safe to
1906 // coalesce them since the live range of vr1025 intersects the
1907 // def of vr1024. This happens because vr1025 is assigned the
1908 // value of the previous iteration of vr1024.
1909 return false;
1910 EliminatedLHSVals.push_back(LHSIt->valno);
1913 // We know this entire LHS live range is okay, so skip it now.
1914 if (++LHSIt == LHSEnd) break;
1915 continue;
1918 if (LHSIt->end < RHSIt->end) {
1919 if (++LHSIt == LHSEnd) break;
1920 } else {
1921 // One interesting case to check here. It's possible that we have
1922 // something like "X3 = Y" which defines a new value number in the LHS,
1923 // and is the last use of this liverange of the RHS. In this case, we
1924 // want to notice this copy (so that it gets coalesced away) even though
1925 // the live ranges don't actually overlap.
1926 if (LHSIt->start == RHSIt->end) {
1927 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
1928 // We already know that this value number is going to be merged in
1929 // if coalescing succeeds. Just skip the liverange.
1930 if (++LHSIt == LHSEnd) break;
1931 } else {
1932 // Otherwise, if this is a copy from the RHS, mark it as being merged
1933 // in.
1934 if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
1935 if (LHSIt->contains(RHSIt->valno->def))
1936 // Here is an interesting situation:
1937 // BB1:
1938 // vr1025 = copy vr1024
1939 // ..
1940 // BB2:
1941 // vr1024 = op
1942 // = vr1025
1943 // Even though vr1025 is copied from vr1024, it's not safe to
1944 // coalesced them since live range of vr1025 intersects the
1945 // def of vr1024. This happens because vr1025 is assigned the
1946 // value of the previous iteration of vr1024.
1947 return false;
1948 EliminatedLHSVals.push_back(LHSIt->valno);
1950 // We know this entire LHS live range is okay, so skip it now.
1951 if (++LHSIt == LHSEnd) break;
1956 if (++RHSIt == RHSEnd) break;
1960 // If we got here, we know that the coalescing will be successful and that
1961 // the value numbers in EliminatedLHSVals will all be merged together. Since
1962 // the most common case is that EliminatedLHSVals has a single number, we
1963 // optimize for it: if there is more than one value, we merge them all into
1964 // the lowest numbered one, then handle the interval as if we were merging
1965 // with one value number.
1966 VNInfo *LHSValNo = NULL;
1967 if (EliminatedLHSVals.size() > 1) {
1968 // Loop through all the equal value numbers merging them into the smallest
1969 // one.
1970 VNInfo *Smallest = EliminatedLHSVals[0];
1971 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1972 if (EliminatedLHSVals[i]->id < Smallest->id) {
1973 // Merge the current notion of the smallest into the smaller one.
1974 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1975 Smallest = EliminatedLHSVals[i];
1976 } else {
1977 // Merge into the smallest.
1978 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1981 LHSValNo = Smallest;
1982 } else if (EliminatedLHSVals.empty()) {
1983 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1984 *tri_->getSuperRegisters(LHS.reg))
1985 // Imprecise sub-register information. Can't handle it.
1986 return false;
1987 llvm_unreachable("No copies from the RHS?");
1988 } else {
1989 LHSValNo = EliminatedLHSVals[0];
1992 // Okay, now that there is a single LHS value number that we're merging the
1993 // RHS into, update the value number info for the LHS to indicate that the
1994 // value number is defined where the RHS value number was.
1995 const VNInfo *VNI = RHS.getValNumInfo(0);
1996 LHSValNo->def = VNI->def;
1997 LHSValNo->setCopy(VNI->getCopy());
1999 // Okay, the final step is to loop over the RHS live intervals, adding them to
2000 // the LHS.
2001 if (VNI->hasPHIKill())
2002 LHSValNo->setHasPHIKill(true);
2003 LHS.addKills(LHSValNo, VNI->kills);
2004 LHS.MergeRangesInAsValue(RHS, LHSValNo);
2006 LHS.ComputeJoinedWeight(RHS);
2008 // Update regalloc hint if both are virtual registers.
2009 if (TargetRegisterInfo::isVirtualRegister(LHS.reg) &&
2010 TargetRegisterInfo::isVirtualRegister(RHS.reg)) {
2011 std::pair<unsigned, unsigned> RHSPref = mri_->getRegAllocationHint(RHS.reg);
2012 std::pair<unsigned, unsigned> LHSPref = mri_->getRegAllocationHint(LHS.reg);
2013 if (RHSPref != LHSPref)
2014 mri_->setRegAllocationHint(LHS.reg, RHSPref.first, RHSPref.second);
2017 // Update the liveintervals of sub-registers.
2018 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg))
2019 for (const unsigned *AS = tri_->getSubRegisters(LHS.reg); *AS; ++AS)
2020 li_->getOrCreateInterval(*AS).MergeInClobberRanges(LHS,
2021 li_->getVNInfoAllocator());
2023 return true;
2026 /// JoinIntervals - Attempt to join these two intervals. On failure, this
2027 /// returns false. Otherwise, if one of the intervals being joined is a
2028 /// physreg, this method always canonicalizes LHS to be it. The output
2029 /// "RHS" will not have been modified, so we can use this information
2030 /// below to update aliases.
2031 bool
2032 SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS,
2033 bool &Swapped) {
2034 // Compute the final value assignment, assuming that the live ranges can be
2035 // coalesced.
2036 SmallVector<int, 16> LHSValNoAssignments;
2037 SmallVector<int, 16> RHSValNoAssignments;
2038 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
2039 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
2040 SmallVector<VNInfo*, 16> NewVNInfo;
2042 // If a live interval is a physical register, conservatively check if any
2043 // of its sub-registers is overlapping the live interval of the virtual
2044 // register. If so, do not coalesce.
2045 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
2046 *tri_->getSubRegisters(LHS.reg)) {
2047 // If it's coalescing a virtual register to a physical register, estimate
2048 // its live interval length. This is the *cost* of scanning an entire live
2049 // interval. If the cost is low, we'll do an exhaustive check instead.
2051 // If this is something like this:
2052 // BB1:
2053 // v1024 = op
2054 // ...
2055 // BB2:
2056 // ...
2057 // RAX = v1024
2059 // That is, the live interval of v1024 crosses a bb. Then we can't rely on
2060 // less conservative check. It's possible a sub-register is defined before
2061 // v1024 (or live in) and live out of BB1.
2062 if (RHS.containsOneValue() &&
2063 li_->intervalIsInOneMBB(RHS) &&
2064 li_->getApproximateInstructionCount(RHS) <= 10) {
2065 // Perform a more exhaustive check for some common cases.
2066 if (li_->conflictsWithPhysRegRef(RHS, LHS.reg, true, JoinedCopies))
2067 return false;
2068 } else {
2069 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
2070 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
2071 DEBUG({
2072 errs() << "Interfere with sub-register ";
2073 li_->getInterval(*SR).print(errs(), tri_);
2075 return false;
2078 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
2079 *tri_->getSubRegisters(RHS.reg)) {
2080 if (LHS.containsOneValue() &&
2081 li_->getApproximateInstructionCount(LHS) <= 10) {
2082 // Perform a more exhaustive check for some common cases.
2083 if (li_->conflictsWithPhysRegRef(LHS, RHS.reg, false, JoinedCopies))
2084 return false;
2085 } else {
2086 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
2087 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
2088 DEBUG({
2089 errs() << "Interfere with sub-register ";
2090 li_->getInterval(*SR).print(errs(), tri_);
2092 return false;
2097 // Compute ultimate value numbers for the LHS and RHS values.
2098 if (RHS.containsOneValue()) {
2099 // Copies from a liveinterval with a single value are simple to handle and
2100 // very common, handle the special case here. This is important, because
2101 // often RHS is small and LHS is large (e.g. a physreg).
2103 // Find out if the RHS is defined as a copy from some value in the LHS.
2104 int RHSVal0DefinedFromLHS = -1;
2105 int RHSValID = -1;
2106 VNInfo *RHSValNoInfo = NULL;
2107 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
2108 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
2109 if (RHSSrcReg == 0 || RHSSrcReg != LHS.reg) {
2110 // If RHS is not defined as a copy from the LHS, we can use simpler and
2111 // faster checks to see if the live ranges are coalescable. This joiner
2112 // can't swap the LHS/RHS intervals though.
2113 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2114 return SimpleJoin(LHS, RHS);
2115 } else {
2116 RHSValNoInfo = RHSValNoInfo0;
2118 } else {
2119 // It was defined as a copy from the LHS, find out what value # it is.
2120 RHSValNoInfo =
2121 LHS.getLiveRangeContaining(li_->getPrevSlot(RHSValNoInfo0->def))->valno;
2122 RHSValID = RHSValNoInfo->id;
2123 RHSVal0DefinedFromLHS = RHSValID;
2126 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2127 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2128 NewVNInfo.resize(LHS.getNumValNums(), NULL);
2130 // Okay, *all* of the values in LHS that are defined as a copy from RHS
2131 // should now get updated.
2132 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2133 i != e; ++i) {
2134 VNInfo *VNI = *i;
2135 unsigned VN = VNI->id;
2136 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
2137 if (LHSSrcReg != RHS.reg) {
2138 // If this is not a copy from the RHS, its value number will be
2139 // unmodified by the coalescing.
2140 NewVNInfo[VN] = VNI;
2141 LHSValNoAssignments[VN] = VN;
2142 } else if (RHSValID == -1) {
2143 // Otherwise, it is a copy from the RHS, and we don't already have a
2144 // value# for it. Keep the current value number, but remember it.
2145 LHSValNoAssignments[VN] = RHSValID = VN;
2146 NewVNInfo[VN] = RHSValNoInfo;
2147 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
2148 } else {
2149 // Otherwise, use the specified value #.
2150 LHSValNoAssignments[VN] = RHSValID;
2151 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
2152 NewVNInfo[VN] = RHSValNoInfo;
2153 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
2156 } else {
2157 NewVNInfo[VN] = VNI;
2158 LHSValNoAssignments[VN] = VN;
2162 assert(RHSValID != -1 && "Didn't find value #?");
2163 RHSValNoAssignments[0] = RHSValID;
2164 if (RHSVal0DefinedFromLHS != -1) {
2165 // This path doesn't go through ComputeUltimateVN so just set
2166 // it to anything.
2167 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
2169 } else {
2170 // Loop over the value numbers of the LHS, seeing if any are defined from
2171 // the RHS.
2172 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2173 i != e; ++i) {
2174 VNInfo *VNI = *i;
2175 if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy?
2176 continue;
2178 // DstReg is known to be a register in the LHS interval. If the src is
2179 // from the RHS interval, we can use its value #.
2180 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
2181 continue;
2183 // Figure out the value # from the RHS.
2184 LHSValsDefinedFromRHS[VNI]=
2185 RHS.getLiveRangeContaining(li_->getPrevSlot(VNI->def))->valno;
2188 // Loop over the value numbers of the RHS, seeing if any are defined from
2189 // the LHS.
2190 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2191 i != e; ++i) {
2192 VNInfo *VNI = *i;
2193 if (VNI->isUnused() || VNI->getCopy() == 0) // Src not defined by a copy?
2194 continue;
2196 // DstReg is known to be a register in the RHS interval. If the src is
2197 // from the LHS interval, we can use its value #.
2198 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
2199 continue;
2201 // Figure out the value # from the LHS.
2202 RHSValsDefinedFromLHS[VNI]=
2203 LHS.getLiveRangeContaining(li_->getPrevSlot(VNI->def))->valno;
2206 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
2207 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
2208 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
2210 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
2211 i != e; ++i) {
2212 VNInfo *VNI = *i;
2213 unsigned VN = VNI->id;
2214 if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
2215 continue;
2216 ComputeUltimateVN(VNI, NewVNInfo,
2217 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
2218 LHSValNoAssignments, RHSValNoAssignments);
2220 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
2221 i != e; ++i) {
2222 VNInfo *VNI = *i;
2223 unsigned VN = VNI->id;
2224 if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
2225 continue;
2226 // If this value number isn't a copy from the LHS, it's a new number.
2227 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
2228 NewVNInfo.push_back(VNI);
2229 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
2230 continue;
2233 ComputeUltimateVN(VNI, NewVNInfo,
2234 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
2235 RHSValNoAssignments, LHSValNoAssignments);
2239 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
2240 // interval lists to see if these intervals are coalescable.
2241 LiveInterval::const_iterator I = LHS.begin();
2242 LiveInterval::const_iterator IE = LHS.end();
2243 LiveInterval::const_iterator J = RHS.begin();
2244 LiveInterval::const_iterator JE = RHS.end();
2246 // Skip ahead until the first place of potential sharing.
2247 if (I->start < J->start) {
2248 I = std::upper_bound(I, IE, J->start);
2249 if (I != LHS.begin()) --I;
2250 } else if (J->start < I->start) {
2251 J = std::upper_bound(J, JE, I->start);
2252 if (J != RHS.begin()) --J;
2255 while (1) {
2256 // Determine if these two live ranges overlap.
2257 bool Overlaps;
2258 if (I->start < J->start) {
2259 Overlaps = I->end > J->start;
2260 } else {
2261 Overlaps = J->end > I->start;
2264 // If so, check value # info to determine if they are really different.
2265 if (Overlaps) {
2266 // If the live range overlap will map to the same value number in the
2267 // result liverange, we can still coalesce them. If not, we can't.
2268 if (LHSValNoAssignments[I->valno->id] !=
2269 RHSValNoAssignments[J->valno->id])
2270 return false;
2273 if (I->end < J->end) {
2274 ++I;
2275 if (I == IE) break;
2276 } else {
2277 ++J;
2278 if (J == JE) break;
2282 // Update kill info. Some live ranges are extended due to copy coalescing.
2283 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
2284 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
2285 VNInfo *VNI = I->first;
2286 unsigned LHSValID = LHSValNoAssignments[VNI->id];
2287 NewVNInfo[LHSValID]->removeKill(VNI->def);
2288 if (VNI->hasPHIKill())
2289 NewVNInfo[LHSValID]->setHasPHIKill(true);
2290 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
2293 // Update kill info. Some live ranges are extended due to copy coalescing.
2294 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
2295 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
2296 VNInfo *VNI = I->first;
2297 unsigned RHSValID = RHSValNoAssignments[VNI->id];
2298 NewVNInfo[RHSValID]->removeKill(VNI->def);
2299 if (VNI->hasPHIKill())
2300 NewVNInfo[RHSValID]->setHasPHIKill(true);
2301 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
2304 // If we get here, we know that we can coalesce the live ranges. Ask the
2305 // intervals to coalesce themselves now.
2306 if ((RHS.ranges.size() > LHS.ranges.size() &&
2307 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
2308 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2309 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo,
2310 mri_);
2311 Swapped = true;
2312 } else {
2313 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
2314 mri_);
2315 Swapped = false;
2317 return true;
2320 namespace {
2321 // DepthMBBCompare - Comparison predicate that sort first based on the loop
2322 // depth of the basic block (the unsigned), and then on the MBB number.
2323 struct DepthMBBCompare {
2324 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
2325 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
2326 if (LHS.first > RHS.first) return true; // Deeper loops first
2327 return LHS.first == RHS.first &&
2328 LHS.second->getNumber() < RHS.second->getNumber();
2333 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
2334 std::vector<CopyRec> &TryAgain) {
2335 DEBUG(errs() << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
2337 std::vector<CopyRec> VirtCopies;
2338 std::vector<CopyRec> PhysCopies;
2339 std::vector<CopyRec> ImpDefCopies;
2340 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2341 MII != E;) {
2342 MachineInstr *Inst = MII++;
2344 // If this isn't a copy nor a extract_subreg, we can't join intervals.
2345 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2346 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
2347 DstReg = Inst->getOperand(0).getReg();
2348 SrcReg = Inst->getOperand(1).getReg();
2349 } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
2350 Inst->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
2351 DstReg = Inst->getOperand(0).getReg();
2352 SrcReg = Inst->getOperand(2).getReg();
2353 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
2354 continue;
2356 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
2357 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
2358 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
2359 ImpDefCopies.push_back(CopyRec(Inst, 0));
2360 else if (SrcIsPhys || DstIsPhys)
2361 PhysCopies.push_back(CopyRec(Inst, 0));
2362 else
2363 VirtCopies.push_back(CopyRec(Inst, 0));
2366 // Try coalescing implicit copies first, followed by copies to / from
2367 // physical registers, then finally copies from virtual registers to
2368 // virtual registers.
2369 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
2370 CopyRec &TheCopy = ImpDefCopies[i];
2371 bool Again = false;
2372 if (!JoinCopy(TheCopy, Again))
2373 if (Again)
2374 TryAgain.push_back(TheCopy);
2376 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
2377 CopyRec &TheCopy = PhysCopies[i];
2378 bool Again = false;
2379 if (!JoinCopy(TheCopy, Again))
2380 if (Again)
2381 TryAgain.push_back(TheCopy);
2383 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
2384 CopyRec &TheCopy = VirtCopies[i];
2385 bool Again = false;
2386 if (!JoinCopy(TheCopy, Again))
2387 if (Again)
2388 TryAgain.push_back(TheCopy);
2392 void SimpleRegisterCoalescing::joinIntervals() {
2393 DEBUG(errs() << "********** JOINING INTERVALS ***********\n");
2395 std::vector<CopyRec> TryAgainList;
2396 if (loopInfo->empty()) {
2397 // If there are no loops in the function, join intervals in function order.
2398 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
2399 I != E; ++I)
2400 CopyCoalesceInMBB(I, TryAgainList);
2401 } else {
2402 // Otherwise, join intervals in inner loops before other intervals.
2403 // Unfortunately we can't just iterate over loop hierarchy here because
2404 // there may be more MBB's than BB's. Collect MBB's for sorting.
2406 // Join intervals in the function prolog first. We want to join physical
2407 // registers with virtual registers before the intervals got too long.
2408 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
2409 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
2410 MachineBasicBlock *MBB = I;
2411 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
2414 // Sort by loop depth.
2415 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2417 // Finally, join intervals in loop nest order.
2418 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2419 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
2422 // Joining intervals can allow other intervals to be joined. Iteratively join
2423 // until we make no progress.
2424 bool ProgressMade = true;
2425 while (ProgressMade) {
2426 ProgressMade = false;
2428 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
2429 CopyRec &TheCopy = TryAgainList[i];
2430 if (!TheCopy.MI)
2431 continue;
2433 bool Again = false;
2434 bool Success = JoinCopy(TheCopy, Again);
2435 if (Success || !Again) {
2436 TheCopy.MI = 0; // Mark this one as done.
2437 ProgressMade = true;
2443 /// Return true if the two specified registers belong to different register
2444 /// classes. The registers may be either phys or virt regs.
2445 bool
2446 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
2447 unsigned RegB) const {
2448 // Get the register classes for the first reg.
2449 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
2450 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
2451 "Shouldn't consider two physregs!");
2452 return !mri_->getRegClass(RegB)->contains(RegA);
2455 // Compare against the regclass for the second reg.
2456 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
2457 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
2458 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
2459 return RegClassA != RegClassB;
2461 return !RegClassA->contains(RegB);
2464 /// lastRegisterUse - Returns the last use of the specific register between
2465 /// cycles Start and End or NULL if there are no uses.
2466 MachineOperand *
2467 SimpleRegisterCoalescing::lastRegisterUse(MachineInstrIndex Start,
2468 MachineInstrIndex End,
2469 unsigned Reg,
2470 MachineInstrIndex &UseIdx) const{
2471 UseIdx = MachineInstrIndex();
2472 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2473 MachineOperand *LastUse = NULL;
2474 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
2475 E = mri_->use_end(); I != E; ++I) {
2476 MachineOperand &Use = I.getOperand();
2477 MachineInstr *UseMI = Use.getParent();
2478 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2479 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2480 SrcReg == DstReg)
2481 // Ignore identity copies.
2482 continue;
2483 MachineInstrIndex Idx = li_->getInstructionIndex(UseMI);
2484 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
2485 LastUse = &Use;
2486 UseIdx = li_->getUseIndex(Idx);
2489 return LastUse;
2492 MachineInstrIndex s = Start;
2493 MachineInstrIndex e = li_->getBaseIndex(li_->getPrevSlot(End));
2494 while (e >= s) {
2495 // Skip deleted instructions
2496 MachineInstr *MI = li_->getInstructionFromIndex(e);
2497 while (e != MachineInstrIndex() && li_->getPrevIndex(e) >= s && !MI) {
2498 e = li_->getPrevIndex(e);
2499 MI = li_->getInstructionFromIndex(e);
2501 if (e < s || MI == NULL)
2502 return NULL;
2504 // Ignore identity copies.
2505 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2506 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2507 SrcReg == DstReg))
2508 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2509 MachineOperand &Use = MI->getOperand(i);
2510 if (Use.isReg() && Use.isUse() && Use.getReg() &&
2511 tri_->regsOverlap(Use.getReg(), Reg)) {
2512 UseIdx = li_->getUseIndex(e);
2513 return &Use;
2517 e = li_->getPrevIndex(e);
2520 return NULL;
2524 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
2525 if (TargetRegisterInfo::isPhysicalRegister(reg))
2526 errs() << tri_->getName(reg);
2527 else
2528 errs() << "%reg" << reg;
2531 void SimpleRegisterCoalescing::releaseMemory() {
2532 JoinedCopies.clear();
2533 ReMatCopies.clear();
2534 ReMatDefs.clear();
2537 bool SimpleRegisterCoalescing::isZeroLengthInterval(LiveInterval *li) const {
2538 for (LiveInterval::Ranges::const_iterator
2539 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
2540 if (li_->getPrevIndex(i->end) > i->start)
2541 return false;
2542 return true;
2546 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2547 mf_ = &fn;
2548 mri_ = &fn.getRegInfo();
2549 tm_ = &fn.getTarget();
2550 tri_ = tm_->getRegisterInfo();
2551 tii_ = tm_->getInstrInfo();
2552 li_ = &getAnalysis<LiveIntervals>();
2553 loopInfo = &getAnalysis<MachineLoopInfo>();
2555 DEBUG(errs() << "********** SIMPLE REGISTER COALESCING **********\n"
2556 << "********** Function: "
2557 << ((Value*)mf_->getFunction())->getName() << '\n');
2559 allocatableRegs_ = tri_->getAllocatableSet(fn);
2560 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2561 E = tri_->regclass_end(); I != E; ++I)
2562 allocatableRCRegs_.insert(std::make_pair(*I,
2563 tri_->getAllocatableSet(fn, *I)));
2565 // Join (coalesce) intervals if requested.
2566 if (EnableJoining) {
2567 joinIntervals();
2568 DEBUG({
2569 errs() << "********** INTERVALS POST JOINING **********\n";
2570 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
2571 I->second->print(errs(), tri_);
2572 errs() << "\n";
2577 // Perform a final pass over the instructions and compute spill weights
2578 // and remove identity moves.
2579 SmallVector<unsigned, 4> DeadDefs;
2580 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2581 mbbi != mbbe; ++mbbi) {
2582 MachineBasicBlock* mbb = mbbi;
2583 unsigned loopDepth = loopInfo->getLoopDepth(mbb);
2585 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2586 mii != mie; ) {
2587 MachineInstr *MI = mii;
2588 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2589 if (JoinedCopies.count(MI)) {
2590 // Delete all coalesced copies.
2591 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
2592 assert((MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
2593 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
2594 MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) &&
2595 "Unrecognized copy instruction");
2596 DstReg = MI->getOperand(0).getReg();
2598 if (MI->registerDefIsDead(DstReg)) {
2599 LiveInterval &li = li_->getInterval(DstReg);
2600 if (!ShortenDeadCopySrcLiveRange(li, MI))
2601 ShortenDeadCopyLiveRange(li, MI);
2603 li_->RemoveMachineInstrFromMaps(MI);
2604 mii = mbbi->erase(mii);
2605 ++numPeep;
2606 continue;
2609 // Now check if this is a remat'ed def instruction which is now dead.
2610 if (ReMatDefs.count(MI)) {
2611 bool isDead = true;
2612 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2613 const MachineOperand &MO = MI->getOperand(i);
2614 if (!MO.isReg())
2615 continue;
2616 unsigned Reg = MO.getReg();
2617 if (!Reg)
2618 continue;
2619 if (TargetRegisterInfo::isVirtualRegister(Reg))
2620 DeadDefs.push_back(Reg);
2621 if (MO.isDead())
2622 continue;
2623 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
2624 !mri_->use_empty(Reg)) {
2625 isDead = false;
2626 break;
2629 if (isDead) {
2630 while (!DeadDefs.empty()) {
2631 unsigned DeadDef = DeadDefs.back();
2632 DeadDefs.pop_back();
2633 RemoveDeadDef(li_->getInterval(DeadDef), MI);
2635 li_->RemoveMachineInstrFromMaps(mii);
2636 mii = mbbi->erase(mii);
2637 continue;
2638 } else
2639 DeadDefs.clear();
2642 // If the move will be an identity move delete it
2643 bool isMove= tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
2644 if (isMove && SrcReg == DstReg) {
2645 if (li_->hasInterval(SrcReg)) {
2646 LiveInterval &RegInt = li_->getInterval(SrcReg);
2647 // If def of this move instruction is dead, remove its live range
2648 // from the dstination register's live interval.
2649 if (MI->registerDefIsDead(DstReg)) {
2650 if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
2651 ShortenDeadCopyLiveRange(RegInt, MI);
2654 li_->RemoveMachineInstrFromMaps(MI);
2655 mii = mbbi->erase(mii);
2656 ++numPeep;
2657 } else {
2658 SmallSet<unsigned, 4> UniqueUses;
2659 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2660 const MachineOperand &mop = MI->getOperand(i);
2661 if (mop.isReg() && mop.getReg() &&
2662 TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
2663 unsigned reg = mop.getReg();
2664 // Multiple uses of reg by the same instruction. It should not
2665 // contribute to spill weight again.
2666 if (UniqueUses.count(reg) != 0)
2667 continue;
2668 LiveInterval &RegInt = li_->getInterval(reg);
2669 RegInt.weight +=
2670 li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
2671 UniqueUses.insert(reg);
2674 ++mii;
2679 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
2680 LiveInterval &LI = *I->second;
2681 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
2682 // If the live interval length is essentially zero, i.e. in every live
2683 // range the use follows def immediately, it doesn't make sense to spill
2684 // it and hope it will be easier to allocate for this li.
2685 if (isZeroLengthInterval(&LI))
2686 LI.weight = HUGE_VALF;
2687 else {
2688 bool isLoad = false;
2689 SmallVector<LiveInterval*, 4> SpillIs;
2690 if (li_->isReMaterializable(LI, SpillIs, isLoad)) {
2691 // If all of the definitions of the interval are re-materializable,
2692 // it is a preferred candidate for spilling. If non of the defs are
2693 // loads, then it's potentially very cheap to re-materialize.
2694 // FIXME: this gets much more complicated once we support non-trivial
2695 // re-materialization.
2696 if (isLoad)
2697 LI.weight *= 0.9F;
2698 else
2699 LI.weight *= 0.5F;
2703 // Slightly prefer live interval that has been assigned a preferred reg.
2704 std::pair<unsigned, unsigned> Hint = mri_->getRegAllocationHint(LI.reg);
2705 if (Hint.first || Hint.second)
2706 LI.weight *= 1.01F;
2708 // Divide the weight of the interval by its size. This encourages
2709 // spilling of intervals that are large and have few uses, and
2710 // discourages spilling of small intervals with many uses.
2711 LI.weight /= li_->getApproximateInstructionCount(LI) * InstrSlots::NUM;
2715 DEBUG(dump());
2716 return true;
2719 /// print - Implement the dump method.
2720 void SimpleRegisterCoalescing::print(raw_ostream &O, const Module* m) const {
2721 li_->print(O, m);
2724 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2725 return new SimpleRegisterCoalescing();
2728 // Make sure that anything that uses RegisterCoalescer pulls in this file...
2729 DEFINING_FILE_FOR(SimpleRegisterCoalescing)