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