Move all work list processing to copyCoalesceWorkList().
[oota-llvm.git] / lib / CodeGen / RegisterCoalescer.cpp
1 //===- RegisterCoalescer.cpp - Generic Register Coalescing Interface -------==//
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 the generic RegisterCoalescer interface which
11 // is used as the common interface used by all clients and
12 // implementations of register coalescing.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "regalloc"
17 #include "RegisterCoalescer.h"
18 #include "LiveDebugVariables.h"
19 #include "RegisterClassInfo.h"
20 #include "VirtRegMap.h"
21
22 #include "llvm/Pass.h"
23 #include "llvm/Value.h"
24 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
30 #include "llvm/Analysis/AliasAnalysis.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineLoopInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/Passes.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/ADT/OwningPtr.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/STLExtras.h"
47 #include <algorithm>
48 #include <cmath>
49 using namespace llvm;
50
51 STATISTIC(numJoins    , "Number of interval joins performed");
52 STATISTIC(numCrossRCs , "Number of cross class joins performed");
53 STATISTIC(numCommutes , "Number of instruction commuting performed");
54 STATISTIC(numExtends  , "Number of copies extended");
55 STATISTIC(NumReMats   , "Number of instructions re-materialized");
56 STATISTIC(numPeep     , "Number of identity moves eliminated after coalescing");
57 STATISTIC(NumInflated , "Number of register classes inflated");
58
59 static cl::opt<bool>
60 EnableJoining("join-liveintervals",
61               cl::desc("Coalesce copies (default=true)"),
62               cl::init(true));
63
64 static cl::opt<bool>
65 VerifyCoalescing("verify-coalescing",
66          cl::desc("Verify machine instrs before and after register coalescing"),
67          cl::Hidden);
68
69 namespace {
70   class RegisterCoalescer : public MachineFunctionPass {
71     MachineFunction* MF;
72     MachineRegisterInfo* MRI;
73     const TargetMachine* TM;
74     const TargetRegisterInfo* TRI;
75     const TargetInstrInfo* TII;
76     LiveIntervals *LIS;
77     LiveDebugVariables *LDV;
78     const MachineLoopInfo* Loops;
79     AliasAnalysis *AA;
80     RegisterClassInfo RegClassInfo;
81
82     /// JoinedCopies - Keep track of copies eliminated due to coalescing.
83     ///
84     SmallPtrSet<MachineInstr*, 32> JoinedCopies;
85
86     /// ReMatCopies - Keep track of copies eliminated due to remat.
87     ///
88     SmallPtrSet<MachineInstr*, 32> ReMatCopies;
89
90     /// ReMatDefs - Keep track of definition instructions which have
91     /// been remat'ed.
92     SmallPtrSet<MachineInstr*, 8> ReMatDefs;
93
94     /// WorkList - Copy instructions yet to be coalesced.
95     SmallVector<MachineInstr*, 8> WorkList;
96
97     /// joinAllIntervals - join compatible live intervals
98     void joinAllIntervals();
99
100     /// copyCoalesceInMBB - Coalesce copies in the specified MBB, putting
101     /// copies that cannot yet be coalesced into WorkList.
102     void copyCoalesceInMBB(MachineBasicBlock *MBB);
103
104     /// copyCoalesceWorkList - Try to coalesce all copies in WorkList after
105     /// position From. Return true if any progress was made.
106     bool copyCoalesceWorkList(unsigned From = 0);
107
108     /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
109     /// which are the src/dst of the copy instruction CopyMI.  This returns
110     /// true if the copy was successfully coalesced away. If it is not
111     /// currently possible to coalesce this interval, but it may be possible if
112     /// other things get coalesced, then it returns true by reference in
113     /// 'Again'.
114     bool joinCopy(MachineInstr *TheCopy, bool &Again);
115
116     /// joinIntervals - Attempt to join these two intervals.  On failure, this
117     /// returns false.  The output "SrcInt" will not have been modified, so we
118     /// can use this information below to update aliases.
119     bool joinIntervals(CoalescerPair &CP);
120
121     /// Attempt joining with a reserved physreg.
122     bool joinReservedPhysReg(CoalescerPair &CP);
123
124     /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
125     /// the source value number is defined by a copy from the destination reg
126     /// see if we can merge these two destination reg valno# into a single
127     /// value number, eliminating a copy.
128     bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
129
130     /// hasOtherReachingDefs - Return true if there are definitions of IntB
131     /// other than BValNo val# that can reach uses of AValno val# of IntA.
132     bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
133                               VNInfo *AValNo, VNInfo *BValNo);
134
135     /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy.
136     /// If the source value number is defined by a commutable instruction and
137     /// its other operand is coalesced to the copy dest register, see if we
138     /// can transform the copy into a noop by commuting the definition.
139     bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
140
141     /// reMaterializeTrivialDef - If the source of a copy is defined by a
142     /// trivial computation, replace the copy by rematerialize the definition.
143     /// If PreserveSrcInt is true, make sure SrcInt is valid after the call.
144     bool reMaterializeTrivialDef(LiveInterval &SrcInt, bool PreserveSrcInt,
145                                  unsigned DstReg, MachineInstr *CopyMI);
146
147     /// canJoinPhys - Return true if a physreg copy should be joined.
148     bool canJoinPhys(CoalescerPair &CP);
149
150     /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
151     /// update the subregister number if it is not zero. If DstReg is a
152     /// physical register and the existing subregister number of the def / use
153     /// being updated is not zero, make sure to set it to the correct physical
154     /// subregister.
155     void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
156
157     /// removeDeadDef - If a def of a live interval is now determined dead,
158     /// remove the val# it defines. If the live interval becomes empty, remove
159     /// it as well.
160     bool removeDeadDef(LiveInterval &li, MachineInstr *DefMI);
161
162     /// markAsJoined - Remember that CopyMI has already been joined.
163     void markAsJoined(MachineInstr *CopyMI);
164
165     /// eliminateUndefCopy - Handle copies of undef values.
166     bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
167
168   public:
169     static char ID; // Class identification, replacement for typeinfo
170     RegisterCoalescer() : MachineFunctionPass(ID) {
171       initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
172     }
173
174     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
175
176     virtual void releaseMemory();
177
178     /// runOnMachineFunction - pass entry point
179     virtual bool runOnMachineFunction(MachineFunction&);
180
181     /// print - Implement the dump method.
182     virtual void print(raw_ostream &O, const Module* = 0) const;
183   };
184 } /// end anonymous namespace
185
186 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
187
188 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
189                       "Simple Register Coalescing", false, false)
190 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
191 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
192 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
193 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
194 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
195 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
196                     "Simple Register Coalescing", false, false)
197
198 char RegisterCoalescer::ID = 0;
199
200 static unsigned compose(const TargetRegisterInfo &tri, unsigned a, unsigned b) {
201   if (!a) return b;
202   if (!b) return a;
203   return tri.composeSubRegIndices(a, b);
204 }
205
206 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
207                         unsigned &Src, unsigned &Dst,
208                         unsigned &SrcSub, unsigned &DstSub) {
209   if (MI->isCopy()) {
210     Dst = MI->getOperand(0).getReg();
211     DstSub = MI->getOperand(0).getSubReg();
212     Src = MI->getOperand(1).getReg();
213     SrcSub = MI->getOperand(1).getSubReg();
214   } else if (MI->isSubregToReg()) {
215     Dst = MI->getOperand(0).getReg();
216     DstSub = compose(tri, MI->getOperand(0).getSubReg(),
217                      MI->getOperand(3).getImm());
218     Src = MI->getOperand(2).getReg();
219     SrcSub = MI->getOperand(2).getSubReg();
220   } else
221     return false;
222   return true;
223 }
224
225 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
226   SrcReg = DstReg = 0;
227   SrcIdx = DstIdx = 0;
228   NewRC = 0;
229   Flipped = CrossClass = false;
230
231   unsigned Src, Dst, SrcSub, DstSub;
232   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
233     return false;
234   Partial = SrcSub || DstSub;
235
236   // If one register is a physreg, it must be Dst.
237   if (TargetRegisterInfo::isPhysicalRegister(Src)) {
238     if (TargetRegisterInfo::isPhysicalRegister(Dst))
239       return false;
240     std::swap(Src, Dst);
241     std::swap(SrcSub, DstSub);
242     Flipped = true;
243   }
244
245   const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
246
247   if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
248     // Eliminate DstSub on a physreg.
249     if (DstSub) {
250       Dst = TRI.getSubReg(Dst, DstSub);
251       if (!Dst) return false;
252       DstSub = 0;
253     }
254
255     // Eliminate SrcSub by picking a corresponding Dst superregister.
256     if (SrcSub) {
257       Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
258       if (!Dst) return false;
259       SrcSub = 0;
260     } else if (!MRI.getRegClass(Src)->contains(Dst)) {
261       return false;
262     }
263   } else {
264     // Both registers are virtual.
265     const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
266     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
267
268     // Both registers have subreg indices.
269     if (SrcSub && DstSub) {
270       // Copies between different sub-registers are never coalescable.
271       if (Src == Dst && SrcSub != DstSub)
272         return false;
273
274       NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
275                                          SrcIdx, DstIdx);
276       if (!NewRC)
277         return false;
278     } else if (DstSub) {
279       // SrcReg will be merged with a sub-register of DstReg.
280       SrcIdx = DstSub;
281       NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
282     } else if (SrcSub) {
283       // DstReg will be merged with a sub-register of SrcReg.
284       DstIdx = SrcSub;
285       NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
286     } else {
287       // This is a straight copy without sub-registers.
288       NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
289     }
290
291     // The combined constraint may be impossible to satisfy.
292     if (!NewRC)
293       return false;
294
295     // Prefer SrcReg to be a sub-register of DstReg.
296     // FIXME: Coalescer should support subregs symmetrically.
297     if (DstIdx && !SrcIdx) {
298       std::swap(Src, Dst);
299       std::swap(SrcIdx, DstIdx);
300       Flipped = !Flipped;
301     }
302
303     CrossClass = NewRC != DstRC || NewRC != SrcRC;
304   }
305   // Check our invariants
306   assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
307   assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
308          "Cannot have a physical SubIdx");
309   SrcReg = Src;
310   DstReg = Dst;
311   return true;
312 }
313
314 bool CoalescerPair::flip() {
315   if (TargetRegisterInfo::isPhysicalRegister(DstReg))
316     return false;
317   std::swap(SrcReg, DstReg);
318   std::swap(SrcIdx, DstIdx);
319   Flipped = !Flipped;
320   return true;
321 }
322
323 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
324   if (!MI)
325     return false;
326   unsigned Src, Dst, SrcSub, DstSub;
327   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
328     return false;
329
330   // Find the virtual register that is SrcReg.
331   if (Dst == SrcReg) {
332     std::swap(Src, Dst);
333     std::swap(SrcSub, DstSub);
334   } else if (Src != SrcReg) {
335     return false;
336   }
337
338   // Now check that Dst matches DstReg.
339   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
340     if (!TargetRegisterInfo::isPhysicalRegister(Dst))
341       return false;
342     assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
343     // DstSub could be set for a physreg from INSERT_SUBREG.
344     if (DstSub)
345       Dst = TRI.getSubReg(Dst, DstSub);
346     // Full copy of Src.
347     if (!SrcSub)
348       return DstReg == Dst;
349     // This is a partial register copy. Check that the parts match.
350     return TRI.getSubReg(DstReg, SrcSub) == Dst;
351   } else {
352     // DstReg is virtual.
353     if (DstReg != Dst)
354       return false;
355     // Registers match, do the subregisters line up?
356     return compose(TRI, SrcIdx, SrcSub) == compose(TRI, DstIdx, DstSub);
357   }
358 }
359
360 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
361   AU.setPreservesCFG();
362   AU.addRequired<AliasAnalysis>();
363   AU.addRequired<LiveIntervals>();
364   AU.addPreserved<LiveIntervals>();
365   AU.addRequired<LiveDebugVariables>();
366   AU.addPreserved<LiveDebugVariables>();
367   AU.addPreserved<SlotIndexes>();
368   AU.addRequired<MachineLoopInfo>();
369   AU.addPreserved<MachineLoopInfo>();
370   AU.addPreservedID(MachineDominatorsID);
371   MachineFunctionPass::getAnalysisUsage(AU);
372 }
373
374 void RegisterCoalescer::markAsJoined(MachineInstr *CopyMI) {
375   /// Joined copies are not deleted immediately, but kept in JoinedCopies.
376   JoinedCopies.insert(CopyMI);
377
378   /// Mark all register operands of CopyMI as <undef> so they won't affect dead
379   /// code elimination.
380   for (MachineInstr::mop_iterator I = CopyMI->operands_begin(),
381        E = CopyMI->operands_end(); I != E; ++I)
382     if (I->isReg())
383       I->setIsUndef(true);
384 }
385
386 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
387 /// being the source and IntB being the dest, thus this defines a value number
388 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
389 /// see if we can merge these two pieces of B into a single value number,
390 /// eliminating a copy.  For example:
391 ///
392 ///  A3 = B0
393 ///    ...
394 ///  B1 = A3      <- this copy
395 ///
396 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
397 /// value number to be replaced with B0 (which simplifies the B liveinterval).
398 ///
399 /// This returns true if an interval was modified.
400 ///
401 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
402                                              MachineInstr *CopyMI) {
403   assert(!CP.isPartial() && "This doesn't work for partial copies.");
404
405   // Bail if there is no dst interval - can happen when merging physical subreg
406   // operations.
407   if (!LIS->hasInterval(CP.getDstReg()))
408     return false;
409
410   LiveInterval &IntA =
411     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
412   LiveInterval &IntB =
413     LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
414   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
415
416   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
417   // the example above.
418   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
419   if (BLR == IntB.end()) return false;
420   VNInfo *BValNo = BLR->valno;
421
422   // Get the location that B is defined at.  Two options: either this value has
423   // an unknown definition point or it is defined at CopyIdx.  If unknown, we
424   // can't process it.
425   if (BValNo->def != CopyIdx) return false;
426
427   // AValNo is the value number in A that defines the copy, A3 in the example.
428   SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
429   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
430   // The live range might not exist after fun with physreg coalescing.
431   if (ALR == IntA.end()) return false;
432   VNInfo *AValNo = ALR->valno;
433
434   // If AValNo is defined as a copy from IntB, we can potentially process this.
435   // Get the instruction that defines this value number.
436   MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
437   if (!CP.isCoalescable(ACopyMI))
438     return false;
439
440   // Get the LiveRange in IntB that this value number starts with.
441   LiveInterval::iterator ValLR =
442     IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
443   if (ValLR == IntB.end())
444     return false;
445
446   // Make sure that the end of the live range is inside the same block as
447   // CopyMI.
448   MachineInstr *ValLREndInst =
449     LIS->getInstructionFromIndex(ValLR->end.getPrevSlot());
450   if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
451     return false;
452
453   // Okay, we now know that ValLR ends in the same block that the CopyMI
454   // live-range starts.  If there are no intervening live ranges between them in
455   // IntB, we can merge them.
456   if (ValLR+1 != BLR) return false;
457
458   // If a live interval is a physical register, conservatively check if any
459   // of its aliases is overlapping the live interval of the virtual register.
460   // If so, do not coalesce.
461   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
462     for (const uint16_t *AS = TRI->getAliasSet(IntB.reg); *AS; ++AS)
463       if (LIS->hasInterval(*AS) && IntA.overlaps(LIS->getInterval(*AS))) {
464         DEBUG({
465             dbgs() << "\t\tInterfere with alias ";
466             LIS->getInterval(*AS).print(dbgs(), TRI);
467           });
468         return false;
469       }
470   }
471
472   DEBUG({
473       dbgs() << "Extending: ";
474       IntB.print(dbgs(), TRI);
475     });
476
477   SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
478   // We are about to delete CopyMI, so need to remove it as the 'instruction
479   // that defines this value #'. Update the valnum with the new defining
480   // instruction #.
481   BValNo->def = FillerStart;
482
483   // Okay, we can merge them.  We need to insert a new liverange:
484   // [ValLR.end, BLR.begin) of either value number, then we merge the
485   // two value numbers.
486   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
487
488   // If the IntB live range is assigned to a physical register, and if that
489   // physreg has sub-registers, update their live intervals as well.
490   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
491     for (const uint16_t *SR = TRI->getSubRegisters(IntB.reg); *SR; ++SR) {
492       if (!LIS->hasInterval(*SR))
493         continue;
494       LiveInterval &SRLI = LIS->getInterval(*SR);
495       SRLI.addRange(LiveRange(FillerStart, FillerEnd,
496                               SRLI.getNextValue(FillerStart,
497                                                 LIS->getVNInfoAllocator())));
498     }
499   }
500
501   // Okay, merge "B1" into the same value number as "B0".
502   if (BValNo != ValLR->valno) {
503     // If B1 is killed by a PHI, then the merged live range must also be killed
504     // by the same PHI, as B0 and B1 can not overlap.
505     bool HasPHIKill = BValNo->hasPHIKill();
506     IntB.MergeValueNumberInto(BValNo, ValLR->valno);
507     if (HasPHIKill)
508       ValLR->valno->setHasPHIKill(true);
509   }
510   DEBUG({
511       dbgs() << "   result = ";
512       IntB.print(dbgs(), TRI);
513       dbgs() << "\n";
514     });
515
516   // If the source instruction was killing the source register before the
517   // merge, unset the isKill marker given the live range has been extended.
518   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
519   if (UIdx != -1) {
520     ValLREndInst->getOperand(UIdx).setIsKill(false);
521   }
522
523   // Rewrite the copy. If the copy instruction was killing the destination
524   // register before the merge, find the last use and trim the live range. That
525   // will also add the isKill marker.
526   CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
527   if (ALR->end == CopyIdx)
528     LIS->shrinkToUses(&IntA);
529
530   ++numExtends;
531   return true;
532 }
533
534 /// hasOtherReachingDefs - Return true if there are definitions of IntB
535 /// other than BValNo val# that can reach uses of AValno val# of IntA.
536 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
537                                              LiveInterval &IntB,
538                                              VNInfo *AValNo,
539                                              VNInfo *BValNo) {
540   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
541        AI != AE; ++AI) {
542     if (AI->valno != AValNo) continue;
543     LiveInterval::Ranges::iterator BI =
544       std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
545     if (BI != IntB.ranges.begin())
546       --BI;
547     for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
548       if (BI->valno == BValNo)
549         continue;
550       if (BI->start <= AI->start && BI->end > AI->start)
551         return true;
552       if (BI->start > AI->start && BI->start < AI->end)
553         return true;
554     }
555   }
556   return false;
557 }
558
559 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy with
560 /// IntA being the source and IntB being the dest, thus this defines a value
561 /// number in IntB.  If the source value number (in IntA) is defined by a
562 /// commutable instruction and its other operand is coalesced to the copy dest
563 /// register, see if we can transform the copy into a noop by commuting the
564 /// definition. For example,
565 ///
566 ///  A3 = op A2 B0<kill>
567 ///    ...
568 ///  B1 = A3      <- this copy
569 ///    ...
570 ///     = op A3   <- more uses
571 ///
572 /// ==>
573 ///
574 ///  B2 = op B0 A2<kill>
575 ///    ...
576 ///  B1 = B2      <- now an identify copy
577 ///    ...
578 ///     = op B2   <- more uses
579 ///
580 /// This returns true if an interval was modified.
581 ///
582 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
583                                                  MachineInstr *CopyMI) {
584   // FIXME: For now, only eliminate the copy by commuting its def when the
585   // source register is a virtual register. We want to guard against cases
586   // where the copy is a back edge copy and commuting the def lengthen the
587   // live interval of the source register to the entire loop.
588   if (CP.isPhys() && CP.isFlipped())
589     return false;
590
591   // Bail if there is no dst interval.
592   if (!LIS->hasInterval(CP.getDstReg()))
593     return false;
594
595   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
596
597   LiveInterval &IntA =
598     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
599   LiveInterval &IntB =
600     LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
601
602   // BValNo is a value number in B that is defined by a copy from A. 'B3' in
603   // the example above.
604   VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
605   if (!BValNo || BValNo->def != CopyIdx)
606     return false;
607
608   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
609
610   // AValNo is the value number in A that defines the copy, A3 in the example.
611   VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
612   assert(AValNo && "COPY source not live");
613
614   // If other defs can reach uses of this def, then it's not safe to perform
615   // the optimization.
616   if (AValNo->isPHIDef() || AValNo->isUnused() || AValNo->hasPHIKill())
617     return false;
618   MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
619   if (!DefMI)
620     return false;
621   if (!DefMI->isCommutable())
622     return false;
623   // If DefMI is a two-address instruction then commuting it will change the
624   // destination register.
625   int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
626   assert(DefIdx != -1);
627   unsigned UseOpIdx;
628   if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
629     return false;
630   unsigned Op1, Op2, NewDstIdx;
631   if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
632     return false;
633   if (Op1 == UseOpIdx)
634     NewDstIdx = Op2;
635   else if (Op2 == UseOpIdx)
636     NewDstIdx = Op1;
637   else
638     return false;
639
640   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
641   unsigned NewReg = NewDstMO.getReg();
642   if (NewReg != IntB.reg || !NewDstMO.isKill())
643     return false;
644
645   // Make sure there are no other definitions of IntB that would reach the
646   // uses which the new definition can reach.
647   if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
648     return false;
649
650   // Abort if the aliases of IntB.reg have values that are not simply the
651   // clobbers from the superreg.
652   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
653     for (const uint16_t *AS = TRI->getAliasSet(IntB.reg); *AS; ++AS)
654       if (LIS->hasInterval(*AS) &&
655           hasOtherReachingDefs(IntA, LIS->getInterval(*AS), AValNo, 0))
656         return false;
657
658   // If some of the uses of IntA.reg is already coalesced away, return false.
659   // It's not possible to determine whether it's safe to perform the coalescing.
660   for (MachineRegisterInfo::use_nodbg_iterator UI =
661          MRI->use_nodbg_begin(IntA.reg),
662        UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
663     MachineInstr *UseMI = &*UI;
664     SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
665     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
666     if (ULR == IntA.end())
667       continue;
668     if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
669       return false;
670   }
671
672   DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
673                << *DefMI);
674
675   // At this point we have decided that it is legal to do this
676   // transformation.  Start by commuting the instruction.
677   MachineBasicBlock *MBB = DefMI->getParent();
678   MachineInstr *NewMI = TII->commuteInstruction(DefMI);
679   if (!NewMI)
680     return false;
681   if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
682       TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
683       !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
684     return false;
685   if (NewMI != DefMI) {
686     LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
687     MachineBasicBlock::iterator Pos = DefMI;
688     MBB->insert(Pos, NewMI);
689     MBB->erase(DefMI);
690   }
691   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
692   NewMI->getOperand(OpIdx).setIsKill();
693
694   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
695   // A = or A, B
696   // ...
697   // B = A
698   // ...
699   // C = A<kill>
700   // ...
701   //   = B
702
703   // Update uses of IntA of the specific Val# with IntB.
704   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
705          UE = MRI->use_end(); UI != UE;) {
706     MachineOperand &UseMO = UI.getOperand();
707     MachineInstr *UseMI = &*UI;
708     ++UI;
709     if (JoinedCopies.count(UseMI))
710       continue;
711     if (UseMI->isDebugValue()) {
712       // FIXME These don't have an instruction index.  Not clear we have enough
713       // info to decide whether to do this replacement or not.  For now do it.
714       UseMO.setReg(NewReg);
715       continue;
716     }
717     SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
718     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
719     if (ULR == IntA.end() || ULR->valno != AValNo)
720       continue;
721     if (TargetRegisterInfo::isPhysicalRegister(NewReg))
722       UseMO.substPhysReg(NewReg, *TRI);
723     else
724       UseMO.setReg(NewReg);
725     if (UseMI == CopyMI)
726       continue;
727     if (!UseMI->isCopy())
728       continue;
729     if (UseMI->getOperand(0).getReg() != IntB.reg ||
730         UseMI->getOperand(0).getSubReg())
731       continue;
732
733     // This copy will become a noop. If it's defining a new val#, merge it into
734     // BValNo.
735     SlotIndex DefIdx = UseIdx.getRegSlot();
736     VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
737     if (!DVNI)
738       continue;
739     DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
740     assert(DVNI->def == DefIdx);
741     BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
742     markAsJoined(UseMI);
743   }
744
745   // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
746   // is updated.
747   VNInfo *ValNo = BValNo;
748   ValNo->def = AValNo->def;
749   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
750        AI != AE; ++AI) {
751     if (AI->valno != AValNo) continue;
752     IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
753   }
754   DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
755
756   IntA.removeValNo(AValNo);
757   DEBUG(dbgs() << "\t\ttrimmed:  " << IntA << '\n');
758   ++numCommutes;
759   return true;
760 }
761
762 /// reMaterializeTrivialDef - If the source of a copy is defined by a trivial
763 /// computation, replace the copy by rematerialize the definition.
764 bool RegisterCoalescer::reMaterializeTrivialDef(LiveInterval &SrcInt,
765                                                 bool preserveSrcInt,
766                                                 unsigned DstReg,
767                                                 MachineInstr *CopyMI) {
768   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
769   LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
770   assert(SrcLR != SrcInt.end() && "Live range not found!");
771   VNInfo *ValNo = SrcLR->valno;
772   if (ValNo->isPHIDef() || ValNo->isUnused())
773     return false;
774   MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
775   if (!DefMI)
776     return false;
777   assert(DefMI && "Defining instruction disappeared");
778   if (!DefMI->isAsCheapAsAMove())
779     return false;
780   if (!TII->isTriviallyReMaterializable(DefMI, AA))
781     return false;
782   bool SawStore = false;
783   if (!DefMI->isSafeToMove(TII, AA, SawStore))
784     return false;
785   const MCInstrDesc &MCID = DefMI->getDesc();
786   if (MCID.getNumDefs() != 1)
787     return false;
788   if (!DefMI->isImplicitDef()) {
789     // Make sure the copy destination register class fits the instruction
790     // definition register class. The mismatch can happen as a result of earlier
791     // extract_subreg, insert_subreg, subreg_to_reg coalescing.
792     const TargetRegisterClass *RC = TII->getRegClass(MCID, 0, TRI, *MF);
793     if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
794       if (MRI->getRegClass(DstReg) != RC)
795         return false;
796     } else if (!RC->contains(DstReg))
797       return false;
798   }
799
800   MachineBasicBlock *MBB = CopyMI->getParent();
801   MachineBasicBlock::iterator MII =
802     llvm::next(MachineBasicBlock::iterator(CopyMI));
803   TII->reMaterialize(*MBB, MII, DstReg, 0, DefMI, *TRI);
804   MachineInstr *NewMI = prior(MII);
805
806   // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
807   // We need to remember these so we can add intervals once we insert
808   // NewMI into SlotIndexes.
809   SmallVector<unsigned, 4> NewMIImplDefs;
810   for (unsigned i = NewMI->getDesc().getNumOperands(),
811          e = NewMI->getNumOperands(); i != e; ++i) {
812     MachineOperand &MO = NewMI->getOperand(i);
813     if (MO.isReg()) {
814       assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
815              TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
816       NewMIImplDefs.push_back(MO.getReg());
817     }
818   }
819
820   // CopyMI may have implicit operands, transfer them over to the newly
821   // rematerialized instruction. And update implicit def interval valnos.
822   for (unsigned i = CopyMI->getDesc().getNumOperands(),
823          e = CopyMI->getNumOperands(); i != e; ++i) {
824     MachineOperand &MO = CopyMI->getOperand(i);
825     if (MO.isReg()) {
826       assert(MO.isImplicit() && "No explicit operands after implict operands.");
827       // Discard VReg implicit defs.
828       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
829         NewMI->addOperand(MO);
830       }
831     }
832   }
833
834   LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
835
836   SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
837   for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
838     unsigned reg = NewMIImplDefs[i];
839     LiveInterval &li = LIS->getInterval(reg);
840     VNInfo *DeadDefVN = li.getNextValue(NewMIIdx.getRegSlot(),
841                                         LIS->getVNInfoAllocator());
842     LiveRange lr(NewMIIdx.getRegSlot(), NewMIIdx.getDeadSlot(), DeadDefVN);
843     li.addRange(lr);
844   }
845
846   CopyMI->eraseFromParent();
847   ReMatCopies.insert(CopyMI);
848   ReMatDefs.insert(DefMI);
849   DEBUG(dbgs() << "Remat: " << *NewMI);
850   ++NumReMats;
851
852   // The source interval can become smaller because we removed a use.
853   if (preserveSrcInt)
854     LIS->shrinkToUses(&SrcInt);
855
856   return true;
857 }
858
859 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
860 /// values, it only removes local variables. When we have a copy like:
861 ///
862 ///   %vreg1 = COPY %vreg2<undef>
863 ///
864 /// We delete the copy and remove the corresponding value number from %vreg1.
865 /// Any uses of that value number are marked as <undef>.
866 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
867                                            const CoalescerPair &CP) {
868   SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
869   LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
870   if (SrcInt->liveAt(Idx))
871     return false;
872   LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
873   if (DstInt->liveAt(Idx))
874     return false;
875
876   // No intervals are live-in to CopyMI - it is undef.
877   if (CP.isFlipped())
878     DstInt = SrcInt;
879   SrcInt = 0;
880
881   VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
882   assert(DeadVNI && "No value defined in DstInt");
883   DstInt->removeValNo(DeadVNI);
884
885   // Find new undef uses.
886   for (MachineRegisterInfo::reg_nodbg_iterator
887          I = MRI->reg_nodbg_begin(DstInt->reg), E = MRI->reg_nodbg_end();
888        I != E; ++I) {
889     MachineOperand &MO = I.getOperand();
890     if (MO.isDef() || MO.isUndef())
891       continue;
892     MachineInstr *MI = MO.getParent();
893     SlotIndex Idx = LIS->getInstructionIndex(MI);
894     if (DstInt->liveAt(Idx))
895       continue;
896     MO.setIsUndef(true);
897     DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
898   }
899   return true;
900 }
901
902 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
903 /// update the subregister number if it is not zero. If DstReg is a
904 /// physical register and the existing subregister number of the def / use
905 /// being updated is not zero, make sure to set it to the correct physical
906 /// subregister.
907 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
908                                           unsigned DstReg,
909                                           unsigned SubIdx) {
910   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
911   LiveInterval &DstInt = LIS->getInterval(DstReg);
912
913   // Update LiveDebugVariables.
914   LDV->renameRegister(SrcReg, DstReg, SubIdx);
915
916   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg);
917        MachineInstr *UseMI = I.skipInstruction();) {
918     bool AlreadyJoined = JoinedCopies.count(UseMI);
919
920     // A PhysReg copy that won't be coalesced can perhaps be rematerialized
921     // instead.
922     if (DstIsPhys) {
923       if (UseMI->isFullCopy() &&
924           UseMI->getOperand(1).getReg() == SrcReg &&
925           UseMI->getOperand(0).getReg() != SrcReg &&
926           UseMI->getOperand(0).getReg() != DstReg &&
927           !AlreadyJoined &&
928           reMaterializeTrivialDef(LIS->getInterval(SrcReg), false,
929                                   UseMI->getOperand(0).getReg(), UseMI))
930         continue;
931     }
932
933     SmallVector<unsigned,8> Ops;
934     bool Reads, Writes;
935     tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
936
937     // If SrcReg wasn't read, it may still be the case that DstReg is live-in
938     // because SrcReg is a sub-register.
939     if (!Reads && SubIdx && !AlreadyJoined)
940       Reads = DstInt.liveAt(LIS->getInstructionIndex(UseMI));
941
942     // Replace SrcReg with DstReg in all UseMI operands.
943     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
944       MachineOperand &MO = UseMI->getOperand(Ops[i]);
945
946       // Adjust <undef> flags in case of sub-register joins. We don't want to
947       // turn a full def into a read-modify-write sub-register def and vice
948       // versa.
949       if (SubIdx && !AlreadyJoined && MO.isDef())
950         MO.setIsUndef(!Reads);
951
952       if (DstIsPhys)
953         MO.substPhysReg(DstReg, *TRI);
954       else
955         MO.substVirtReg(DstReg, SubIdx, *TRI);
956     }
957
958     // This instruction is a copy that will be removed.
959     if (AlreadyJoined)
960       continue;
961
962     DEBUG({
963         dbgs() << "\t\tupdated: ";
964         if (!UseMI->isDebugValue())
965           dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
966         dbgs() << *UseMI;
967       });
968   }
969 }
970
971 /// removeIntervalIfEmpty - Check if the live interval of a physical register
972 /// is empty, if so remove it and also remove the empty intervals of its
973 /// sub-registers. Return true if live interval is removed.
974 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *LIS,
975                                   const TargetRegisterInfo *TRI) {
976   if (li.empty()) {
977     if (TargetRegisterInfo::isPhysicalRegister(li.reg))
978       for (const uint16_t* SR = TRI->getSubRegisters(li.reg); *SR; ++SR) {
979         if (!LIS->hasInterval(*SR))
980           continue;
981         LiveInterval &sli = LIS->getInterval(*SR);
982         if (sli.empty())
983           LIS->removeInterval(*SR);
984       }
985     LIS->removeInterval(li.reg);
986     return true;
987   }
988   return false;
989 }
990
991 /// removeDeadDef - If a def of a live interval is now determined dead, remove
992 /// the val# it defines. If the live interval becomes empty, remove it as well.
993 bool RegisterCoalescer::removeDeadDef(LiveInterval &li, MachineInstr *DefMI) {
994   SlotIndex DefIdx = LIS->getInstructionIndex(DefMI).getRegSlot();
995   LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
996   if (DefIdx != MLR->valno->def)
997     return false;
998   li.removeValNo(MLR->valno);
999   return removeIntervalIfEmpty(li, LIS, TRI);
1000 }
1001
1002 /// canJoinPhys - Return true if a copy involving a physreg should be joined.
1003 bool RegisterCoalescer::canJoinPhys(CoalescerPair &CP) {
1004   /// Always join simple intervals that are defined by a single copy from a
1005   /// reserved register. This doesn't increase register pressure, so it is
1006   /// always beneficial.
1007   if (!RegClassInfo.isReserved(CP.getDstReg())) {
1008     DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
1009     return false;
1010   }
1011
1012   LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1013   if (CP.isFlipped() && JoinVInt.containsOneValue())
1014     return true;
1015
1016   DEBUG(dbgs() << "\tCannot join defs into reserved register.\n");
1017   return false;
1018 }
1019
1020 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1021 /// which are the src/dst of the copy instruction CopyMI.  This returns true
1022 /// if the copy was successfully coalesced away. If it is not currently
1023 /// possible to coalesce this interval, but it may be possible if other
1024 /// things get coalesced, then it returns true by reference in 'Again'.
1025 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
1026
1027   Again = false;
1028   if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1029     return false; // Already done.
1030
1031   DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1032
1033   CoalescerPair CP(*TII, *TRI);
1034   if (!CP.setRegisters(CopyMI)) {
1035     DEBUG(dbgs() << "\tNot coalescable.\n");
1036     return false;
1037   }
1038
1039   // If they are already joined we continue.
1040   if (CP.getSrcReg() == CP.getDstReg()) {
1041     markAsJoined(CopyMI);
1042     DEBUG(dbgs() << "\tCopy already coalesced.\n");
1043     return false;  // Not coalescable.
1044   }
1045
1046   // Eliminate undefs.
1047   if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
1048     markAsJoined(CopyMI);
1049     DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
1050     return false;  // Not coalescable.
1051   }
1052
1053   // Enforce policies.
1054   if (CP.isPhys()) {
1055     DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1056                  << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
1057                  << '\n');
1058     if (!canJoinPhys(CP)) {
1059       // Before giving up coalescing, if definition of source is defined by
1060       // trivial computation, try rematerializing it.
1061       if (!CP.isFlipped() &&
1062           reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()), true,
1063                                   CP.getDstReg(), CopyMI))
1064         return true;
1065       return false;
1066     }
1067   } else {
1068     DEBUG({
1069       dbgs() << "\tConsidering merging to " << CP.getNewRC()->getName()
1070              << " with ";
1071       if (CP.getDstIdx() && CP.getSrcIdx())
1072         dbgs() << PrintReg(CP.getDstReg()) << " in "
1073                << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
1074                << PrintReg(CP.getSrcReg()) << " in "
1075                << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
1076       else
1077         dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
1078                << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
1079     });
1080
1081     // When possible, let DstReg be the larger interval.
1082     if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).ranges.size() >
1083                            LIS->getInterval(CP.getDstReg()).ranges.size())
1084       CP.flip();
1085   }
1086
1087   // Okay, attempt to join these two intervals.  On failure, this returns false.
1088   // Otherwise, if one of the intervals being joined is a physreg, this method
1089   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1090   // been modified, so we can use this information below to update aliases.
1091   if (!joinIntervals(CP)) {
1092     // Coalescing failed.
1093
1094     // If definition of source is defined by trivial computation, try
1095     // rematerializing it.
1096     if (!CP.isFlipped() &&
1097         reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()), true,
1098                                 CP.getDstReg(), CopyMI))
1099       return true;
1100
1101     // If we can eliminate the copy without merging the live ranges, do so now.
1102     if (!CP.isPartial()) {
1103       if (adjustCopiesBackFrom(CP, CopyMI) ||
1104           removeCopyByCommutingDef(CP, CopyMI)) {
1105         markAsJoined(CopyMI);
1106         DEBUG(dbgs() << "\tTrivial!\n");
1107         return true;
1108       }
1109     }
1110
1111     // Otherwise, we are unable to join the intervals.
1112     DEBUG(dbgs() << "\tInterference!\n");
1113     Again = true;  // May be possible to coalesce later.
1114     return false;
1115   }
1116
1117   // Coalescing to a virtual register that is of a sub-register class of the
1118   // other. Make sure the resulting register is set to the right register class.
1119   if (CP.isCrossClass()) {
1120     ++numCrossRCs;
1121     MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1122   }
1123
1124   // Remember to delete the copy instruction.
1125   markAsJoined(CopyMI);
1126
1127   // Rewrite all SrcReg operands to DstReg.
1128   // Also update DstReg operands to include DstIdx if it is set.
1129   if (CP.getDstIdx())
1130     updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1131   updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1132
1133   // SrcReg is guaranteed to be the register whose live interval that is
1134   // being merged.
1135   LIS->removeInterval(CP.getSrcReg());
1136
1137   // Update regalloc hint.
1138   TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1139
1140   DEBUG({
1141     LiveInterval &DstInt = LIS->getInterval(CP.getDstReg());
1142     dbgs() << "\tJoined. Result = ";
1143     DstInt.print(dbgs(), TRI);
1144     dbgs() << "\n";
1145   });
1146
1147   ++numJoins;
1148   return true;
1149 }
1150
1151 /// Attempt joining with a reserved physreg.
1152 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1153   assert(CP.isPhys() && "Must be a physreg copy");
1154   assert(RegClassInfo.isReserved(CP.getDstReg()) && "Not a reserved register");
1155   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1156   DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), TRI); dbgs() << "\n"; });
1157
1158   assert(CP.isFlipped() && RHS.containsOneValue() &&
1159          "Invalid join with reserved register");
1160
1161   // Optimization for reserved registers like ESP. We can only merge with a
1162   // reserved physreg if RHS has a single value that is a copy of CP.DstReg().
1163   // The live range of the reserved register will look like a set of dead defs
1164   // - we don't properly track the live range of reserved registers.
1165
1166   // Deny any overlapping intervals.  This depends on all the reserved
1167   // register live ranges to look like dead defs.
1168   for (const uint16_t *AS = TRI->getOverlaps(CP.getDstReg()); *AS; ++AS) {
1169     if (!LIS->hasInterval(*AS)) {
1170       // Make sure at least DstReg itself exists before attempting a join.
1171       if (*AS == CP.getDstReg())
1172         LIS->getOrCreateInterval(CP.getDstReg());
1173       continue;
1174     }
1175     if (RHS.overlaps(LIS->getInterval(*AS))) {
1176       DEBUG(dbgs() << "\t\tInterference: " << PrintReg(*AS, TRI) << '\n');
1177       return false;
1178     }
1179   }
1180   // Skip any value computations, we are not adding new values to the
1181   // reserved register.  Also skip merging the live ranges, the reserved
1182   // register live range doesn't need to be accurate as long as all the
1183   // defs are there.
1184   return true;
1185 }
1186
1187 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1188 /// compute what the resultant value numbers for each value in the input two
1189 /// ranges will be.  This is complicated by copies between the two which can
1190 /// and will commonly cause multiple value numbers to be merged into one.
1191 ///
1192 /// VN is the value number that we're trying to resolve.  InstDefiningValue
1193 /// keeps track of the new InstDefiningValue assignment for the result
1194 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
1195 /// whether a value in this or other is a copy from the opposite set.
1196 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1197 /// already been assigned.
1198 ///
1199 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1200 /// contains the value number the copy is from.
1201 ///
1202 static unsigned ComputeUltimateVN(VNInfo *VNI,
1203                                   SmallVector<VNInfo*, 16> &NewVNInfo,
1204                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1205                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1206                                   SmallVector<int, 16> &ThisValNoAssignments,
1207                                   SmallVector<int, 16> &OtherValNoAssignments) {
1208   unsigned VN = VNI->id;
1209
1210   // If the VN has already been computed, just return it.
1211   if (ThisValNoAssignments[VN] >= 0)
1212     return ThisValNoAssignments[VN];
1213   assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1214
1215   // If this val is not a copy from the other val, then it must be a new value
1216   // number in the destination.
1217   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1218   if (I == ThisFromOther.end()) {
1219     NewVNInfo.push_back(VNI);
1220     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1221   }
1222   VNInfo *OtherValNo = I->second;
1223
1224   // Otherwise, this *is* a copy from the RHS.  If the other side has already
1225   // been computed, return it.
1226   if (OtherValNoAssignments[OtherValNo->id] >= 0)
1227     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1228
1229   // Mark this value number as currently being computed, then ask what the
1230   // ultimate value # of the other value is.
1231   ThisValNoAssignments[VN] = -2;
1232   unsigned UltimateVN =
1233     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1234                       OtherValNoAssignments, ThisValNoAssignments);
1235   return ThisValNoAssignments[VN] = UltimateVN;
1236 }
1237
1238
1239 // Find out if we have something like
1240 // A = X
1241 // B = X
1242 // if so, we can pretend this is actually
1243 // A = X
1244 // B = A
1245 // which allows us to coalesce A and B.
1246 // VNI is the definition of B. LR is the life range of A that includes
1247 // the slot just before B. If we return true, we add "B = X" to DupCopies.
1248 // This implies that A dominates B.
1249 static bool RegistersDefinedFromSameValue(LiveIntervals &li,
1250                                           const TargetRegisterInfo &tri,
1251                                           CoalescerPair &CP,
1252                                           VNInfo *VNI,
1253                                           LiveRange *LR,
1254                                      SmallVector<MachineInstr*, 8> &DupCopies) {
1255   // FIXME: This is very conservative. For example, we don't handle
1256   // physical registers.
1257
1258   MachineInstr *MI = li.getInstructionFromIndex(VNI->def);
1259
1260   if (!MI || !MI->isFullCopy() || CP.isPartial() || CP.isPhys())
1261     return false;
1262
1263   unsigned Dst = MI->getOperand(0).getReg();
1264   unsigned Src = MI->getOperand(1).getReg();
1265
1266   if (!TargetRegisterInfo::isVirtualRegister(Src) ||
1267       !TargetRegisterInfo::isVirtualRegister(Dst))
1268     return false;
1269
1270   unsigned A = CP.getDstReg();
1271   unsigned B = CP.getSrcReg();
1272
1273   if (B == Dst)
1274     std::swap(A, B);
1275   assert(Dst == A);
1276
1277   VNInfo *Other = LR->valno;
1278   const MachineInstr *OtherMI = li.getInstructionFromIndex(Other->def);
1279
1280   if (!OtherMI || !OtherMI->isFullCopy())
1281     return false;
1282
1283   unsigned OtherDst = OtherMI->getOperand(0).getReg();
1284   unsigned OtherSrc = OtherMI->getOperand(1).getReg();
1285
1286   if (!TargetRegisterInfo::isVirtualRegister(OtherSrc) ||
1287       !TargetRegisterInfo::isVirtualRegister(OtherDst))
1288     return false;
1289
1290   assert(OtherDst == B);
1291
1292   if (Src != OtherSrc)
1293     return false;
1294
1295   // If the copies use two different value numbers of X, we cannot merge
1296   // A and B.
1297   LiveInterval &SrcInt = li.getInterval(Src);
1298   // getVNInfoBefore returns NULL for undef copies. In this case, the
1299   // optimization is still safe.
1300   if (SrcInt.getVNInfoBefore(Other->def) != SrcInt.getVNInfoBefore(VNI->def))
1301     return false;
1302
1303   DupCopies.push_back(MI);
1304
1305   return true;
1306 }
1307
1308 /// joinIntervals - Attempt to join these two intervals.  On failure, this
1309 /// returns false.
1310 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
1311   // Handle physreg joins separately.
1312   if (CP.isPhys())
1313     return joinReservedPhysReg(CP);
1314
1315   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1316   DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), TRI); dbgs() << "\n"; });
1317
1318   // Compute the final value assignment, assuming that the live ranges can be
1319   // coalesced.
1320   SmallVector<int, 16> LHSValNoAssignments;
1321   SmallVector<int, 16> RHSValNoAssignments;
1322   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1323   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1324   SmallVector<VNInfo*, 16> NewVNInfo;
1325
1326   SmallVector<MachineInstr*, 8> DupCopies;
1327
1328   LiveInterval &LHS = LIS->getOrCreateInterval(CP.getDstReg());
1329   DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), TRI); dbgs() << "\n"; });
1330
1331   // Loop over the value numbers of the LHS, seeing if any are defined from
1332   // the RHS.
1333   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1334        i != e; ++i) {
1335     VNInfo *VNI = *i;
1336     if (VNI->isUnused() || VNI->isPHIDef())
1337       continue;
1338     MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1339     assert(MI && "Missing def");
1340     if (!MI->isCopyLike())  // Src not defined by a copy?
1341       continue;
1342
1343     // Figure out the value # from the RHS.
1344     LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1345     // The copy could be to an aliased physreg.
1346     if (!lr) continue;
1347
1348     // DstReg is known to be a register in the LHS interval.  If the src is
1349     // from the RHS interval, we can use its value #.
1350     if (!CP.isCoalescable(MI) &&
1351         !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies))
1352       continue;
1353
1354     LHSValsDefinedFromRHS[VNI] = lr->valno;
1355   }
1356
1357   // Loop over the value numbers of the RHS, seeing if any are defined from
1358   // the LHS.
1359   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1360        i != e; ++i) {
1361     VNInfo *VNI = *i;
1362     if (VNI->isUnused() || VNI->isPHIDef())
1363       continue;
1364     MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1365     assert(MI && "Missing def");
1366     if (!MI->isCopyLike())  // Src not defined by a copy?
1367       continue;
1368
1369     // Figure out the value # from the LHS.
1370     LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1371     // The copy could be to an aliased physreg.
1372     if (!lr) continue;
1373
1374     // DstReg is known to be a register in the RHS interval.  If the src is
1375     // from the LHS interval, we can use its value #.
1376     if (!CP.isCoalescable(MI) &&
1377         !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies))
1378         continue;
1379
1380     RHSValsDefinedFromLHS[VNI] = lr->valno;
1381   }
1382
1383   LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1384   RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1385   NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1386
1387   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1388        i != e; ++i) {
1389     VNInfo *VNI = *i;
1390     unsigned VN = VNI->id;
1391     if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1392       continue;
1393     ComputeUltimateVN(VNI, NewVNInfo,
1394                       LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1395                       LHSValNoAssignments, RHSValNoAssignments);
1396   }
1397   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1398        i != e; ++i) {
1399     VNInfo *VNI = *i;
1400     unsigned VN = VNI->id;
1401     if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1402       continue;
1403     // If this value number isn't a copy from the LHS, it's a new number.
1404     if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1405       NewVNInfo.push_back(VNI);
1406       RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1407       continue;
1408     }
1409
1410     ComputeUltimateVN(VNI, NewVNInfo,
1411                       RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1412                       RHSValNoAssignments, LHSValNoAssignments);
1413   }
1414
1415   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1416   // interval lists to see if these intervals are coalescable.
1417   LiveInterval::const_iterator I = LHS.begin();
1418   LiveInterval::const_iterator IE = LHS.end();
1419   LiveInterval::const_iterator J = RHS.begin();
1420   LiveInterval::const_iterator JE = RHS.end();
1421
1422   // Skip ahead until the first place of potential sharing.
1423   if (I != IE && J != JE) {
1424     if (I->start < J->start) {
1425       I = std::upper_bound(I, IE, J->start);
1426       if (I != LHS.begin()) --I;
1427     } else if (J->start < I->start) {
1428       J = std::upper_bound(J, JE, I->start);
1429       if (J != RHS.begin()) --J;
1430     }
1431   }
1432
1433   while (I != IE && J != JE) {
1434     // Determine if these two live ranges overlap.
1435     bool Overlaps;
1436     if (I->start < J->start) {
1437       Overlaps = I->end > J->start;
1438     } else {
1439       Overlaps = J->end > I->start;
1440     }
1441
1442     // If so, check value # info to determine if they are really different.
1443     if (Overlaps) {
1444       // If the live range overlap will map to the same value number in the
1445       // result liverange, we can still coalesce them.  If not, we can't.
1446       if (LHSValNoAssignments[I->valno->id] !=
1447           RHSValNoAssignments[J->valno->id])
1448         return false;
1449     }
1450
1451     if (I->end < J->end)
1452       ++I;
1453     else
1454       ++J;
1455   }
1456
1457   // Update kill info. Some live ranges are extended due to copy coalescing.
1458   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1459          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1460     VNInfo *VNI = I->first;
1461     unsigned LHSValID = LHSValNoAssignments[VNI->id];
1462     if (VNI->hasPHIKill())
1463       NewVNInfo[LHSValID]->setHasPHIKill(true);
1464   }
1465
1466   // Update kill info. Some live ranges are extended due to copy coalescing.
1467   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1468          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1469     VNInfo *VNI = I->first;
1470     unsigned RHSValID = RHSValNoAssignments[VNI->id];
1471     if (VNI->hasPHIKill())
1472       NewVNInfo[RHSValID]->setHasPHIKill(true);
1473   }
1474
1475   if (LHSValNoAssignments.empty())
1476     LHSValNoAssignments.push_back(-1);
1477   if (RHSValNoAssignments.empty())
1478     RHSValNoAssignments.push_back(-1);
1479
1480   SmallVector<unsigned, 8> SourceRegisters;
1481   for (SmallVector<MachineInstr*, 8>::iterator I = DupCopies.begin(),
1482          E = DupCopies.end(); I != E; ++I) {
1483     MachineInstr *MI = *I;
1484
1485     // We have pretended that the assignment to B in
1486     // A = X
1487     // B = X
1488     // was actually a copy from A. Now that we decided to coalesce A and B,
1489     // transform the code into
1490     // A = X
1491     // X = X
1492     // and mark the X as coalesced to keep the illusion.
1493     unsigned Src = MI->getOperand(1).getReg();
1494     SourceRegisters.push_back(Src);
1495     MI->getOperand(0).substVirtReg(Src, 0, *TRI);
1496
1497     markAsJoined(MI);
1498   }
1499
1500   // If B = X was the last use of X in a liverange, we have to shrink it now
1501   // that B = X is gone.
1502   for (SmallVector<unsigned, 8>::iterator I = SourceRegisters.begin(),
1503          E = SourceRegisters.end(); I != E; ++I) {
1504     LIS->shrinkToUses(&LIS->getInterval(*I));
1505   }
1506
1507   // If we get here, we know that we can coalesce the live ranges.  Ask the
1508   // intervals to coalesce themselves now.
1509   LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1510            MRI);
1511   return true;
1512 }
1513
1514 namespace {
1515   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1516   // depth of the basic block (the unsigned), and then on the MBB number.
1517   struct DepthMBBCompare {
1518     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1519     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1520       // Deeper loops first
1521       if (LHS.first != RHS.first)
1522         return LHS.first > RHS.first;
1523
1524       // Prefer blocks that are more connected in the CFG. This takes care of
1525       // the most difficult copies first while intervals are short.
1526       unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1527       unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1528       if (cl != cr)
1529         return cl > cr;
1530
1531       // As a last resort, sort by block number.
1532       return LHS.second->getNumber() < RHS.second->getNumber();
1533     }
1534   };
1535 }
1536
1537 // Try joining WorkList copies starting from index From.
1538 // Null out any successful joins.
1539 bool RegisterCoalescer::copyCoalesceWorkList(unsigned From) {
1540   assert(From <= WorkList.size() && "Out of range");
1541   bool Progress = false;
1542   for (unsigned i = From, e = WorkList.size(); i != e; ++i) {
1543     if (!WorkList[i])
1544       continue;
1545     bool Again = false;
1546     bool Success = joinCopy(WorkList[i], Again);
1547     Progress |= Success;
1548     if (Success || !Again)
1549       WorkList[i] = 0;
1550   }
1551   return Progress;
1552 }
1553
1554 void
1555 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
1556   DEBUG(dbgs() << MBB->getName() << ":\n");
1557
1558   // Collect all copy-like instructions in MBB. Don't start coalescing anything
1559   // yet, it might invalidate the iterator.
1560   const unsigned PrevSize = WorkList.size();
1561   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1562        MII != E; ++MII)
1563     if (MII->isCopyLike())
1564       WorkList.push_back(MII);
1565
1566   // Try coalescing the collected copies immediately, and remove the nulls.
1567   // This prevents the WorkList from getting too large since most copies are
1568   // joinable on the first attempt.
1569   if (copyCoalesceWorkList(PrevSize))
1570     WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
1571                                (MachineInstr*)0), WorkList.end());
1572 }
1573
1574 void RegisterCoalescer::joinAllIntervals() {
1575   DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1576   assert(WorkList.empty() && "Old data still around.");
1577
1578   if (Loops->empty()) {
1579     // If there are no loops in the function, join intervals in function order.
1580     for (MachineFunction::iterator I = MF->begin(), E = MF->end();
1581          I != E; ++I)
1582       copyCoalesceInMBB(I);
1583   } else {
1584     // Otherwise, join intervals in inner loops before other intervals.
1585     // Unfortunately we can't just iterate over loop hierarchy here because
1586     // there may be more MBB's than BB's.  Collect MBB's for sorting.
1587
1588     // Join intervals in the function prolog first. We want to join physical
1589     // registers with virtual registers before the intervals got too long.
1590     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1591     for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
1592       MachineBasicBlock *MBB = I;
1593       MBBs.push_back(std::make_pair(Loops->getLoopDepth(MBB), I));
1594     }
1595
1596     // Sort by loop depth.
1597     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1598
1599     // Finally, join intervals in loop nest order.
1600     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1601       copyCoalesceInMBB(MBBs[i].second);
1602   }
1603
1604   // Joining intervals can allow other intervals to be joined.  Iteratively join
1605   // until we make no progress.
1606   while (copyCoalesceWorkList())
1607     /* empty */ ;
1608 }
1609
1610 void RegisterCoalescer::releaseMemory() {
1611   JoinedCopies.clear();
1612   ReMatCopies.clear();
1613   ReMatDefs.clear();
1614   WorkList.clear();
1615 }
1616
1617 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
1618   MF = &fn;
1619   MRI = &fn.getRegInfo();
1620   TM = &fn.getTarget();
1621   TRI = TM->getRegisterInfo();
1622   TII = TM->getInstrInfo();
1623   LIS = &getAnalysis<LiveIntervals>();
1624   LDV = &getAnalysis<LiveDebugVariables>();
1625   AA = &getAnalysis<AliasAnalysis>();
1626   Loops = &getAnalysis<MachineLoopInfo>();
1627
1628   DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1629                << "********** Function: "
1630                << ((Value*)MF->getFunction())->getName() << '\n');
1631
1632   if (VerifyCoalescing)
1633     MF->verify(this, "Before register coalescing");
1634
1635   RegClassInfo.runOnMachineFunction(fn);
1636
1637   // Join (coalesce) intervals if requested.
1638   if (EnableJoining) {
1639     joinAllIntervals();
1640     DEBUG({
1641         dbgs() << "********** INTERVALS POST JOINING **********\n";
1642         for (LiveIntervals::iterator I = LIS->begin(), E = LIS->end();
1643              I != E; ++I){
1644           I->second->print(dbgs(), TRI);
1645           dbgs() << "\n";
1646         }
1647       });
1648   }
1649
1650   // Perform a final pass over the instructions and compute spill weights
1651   // and remove identity moves.
1652   SmallVector<unsigned, 4> DeadDefs, InflateRegs;
1653   for (MachineFunction::iterator mbbi = MF->begin(), mbbe = MF->end();
1654        mbbi != mbbe; ++mbbi) {
1655     MachineBasicBlock* mbb = mbbi;
1656     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1657          mii != mie; ) {
1658       MachineInstr *MI = mii;
1659       if (JoinedCopies.count(MI)) {
1660         // Delete all coalesced copies.
1661         bool DoDelete = true;
1662         assert(MI->isCopyLike() && "Unrecognized copy instruction");
1663         unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1664         unsigned DstReg = MI->getOperand(0).getReg();
1665
1666         // Collect candidates for register class inflation.
1667         if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1668             RegClassInfo.isProperSubClass(MRI->getRegClass(SrcReg)))
1669           InflateRegs.push_back(SrcReg);
1670         if (TargetRegisterInfo::isVirtualRegister(DstReg) &&
1671             RegClassInfo.isProperSubClass(MRI->getRegClass(DstReg)))
1672           InflateRegs.push_back(DstReg);
1673
1674         if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1675             MI->getNumOperands() > 2)
1676           // Do not delete extract_subreg, insert_subreg of physical
1677           // registers unless the definition is dead. e.g.
1678           // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1679           // or else the scavenger may complain. LowerSubregs will
1680           // delete them later.
1681           DoDelete = false;
1682
1683         if (MI->allDefsAreDead()) {
1684           if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1685               LIS->hasInterval(SrcReg))
1686             LIS->shrinkToUses(&LIS->getInterval(SrcReg));
1687           DoDelete = true;
1688         }
1689         if (!DoDelete) {
1690           // We need the instruction to adjust liveness, so make it a KILL.
1691           if (MI->isSubregToReg()) {
1692             MI->RemoveOperand(3);
1693             MI->RemoveOperand(1);
1694           }
1695           MI->setDesc(TII->get(TargetOpcode::KILL));
1696           mii = llvm::next(mii);
1697         } else {
1698           LIS->RemoveMachineInstrFromMaps(MI);
1699           mii = mbbi->erase(mii);
1700           ++numPeep;
1701         }
1702         continue;
1703       }
1704
1705       // Now check if this is a remat'ed def instruction which is now dead.
1706       if (ReMatDefs.count(MI)) {
1707         bool isDead = true;
1708         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1709           const MachineOperand &MO = MI->getOperand(i);
1710           if (!MO.isReg())
1711             continue;
1712           unsigned Reg = MO.getReg();
1713           if (!Reg)
1714             continue;
1715           DeadDefs.push_back(Reg);
1716           if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1717             // Remat may also enable register class inflation.
1718             if (RegClassInfo.isProperSubClass(MRI->getRegClass(Reg)))
1719               InflateRegs.push_back(Reg);
1720           }
1721           if (MO.isDead())
1722             continue;
1723           if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1724               !MRI->use_nodbg_empty(Reg)) {
1725             isDead = false;
1726             break;
1727           }
1728         }
1729         if (isDead) {
1730           while (!DeadDefs.empty()) {
1731             unsigned DeadDef = DeadDefs.back();
1732             DeadDefs.pop_back();
1733             removeDeadDef(LIS->getInterval(DeadDef), MI);
1734           }
1735           LIS->RemoveMachineInstrFromMaps(mii);
1736           mii = mbbi->erase(mii);
1737           continue;
1738         } else
1739           DeadDefs.clear();
1740       }
1741
1742       ++mii;
1743
1744       // Check for now unnecessary kill flags.
1745       if (LIS->isNotInMIMap(MI)) continue;
1746       SlotIndex DefIdx = LIS->getInstructionIndex(MI).getRegSlot();
1747       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1748         MachineOperand &MO = MI->getOperand(i);
1749         if (!MO.isReg() || !MO.isKill()) continue;
1750         unsigned reg = MO.getReg();
1751         if (!reg || !LIS->hasInterval(reg)) continue;
1752         if (!LIS->getInterval(reg).killedAt(DefIdx)) {
1753           MO.setIsKill(false);
1754           continue;
1755         }
1756         // When leaving a kill flag on a physreg, check if any subregs should
1757         // remain alive.
1758         if (!TargetRegisterInfo::isPhysicalRegister(reg))
1759           continue;
1760         for (const uint16_t *SR = TRI->getSubRegisters(reg);
1761              unsigned S = *SR; ++SR)
1762           if (LIS->hasInterval(S) && LIS->getInterval(S).liveAt(DefIdx))
1763             MI->addRegisterDefined(S, TRI);
1764       }
1765     }
1766   }
1767
1768   // After deleting a lot of copies, register classes may be less constrained.
1769   // Removing sub-register opreands may alow GR32_ABCD -> GR32 and DPR_VFP2 ->
1770   // DPR inflation.
1771   array_pod_sort(InflateRegs.begin(), InflateRegs.end());
1772   InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
1773                     InflateRegs.end());
1774   DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
1775   for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
1776     unsigned Reg = InflateRegs[i];
1777     if (MRI->reg_nodbg_empty(Reg))
1778       continue;
1779     if (MRI->recomputeRegClass(Reg, *TM)) {
1780       DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
1781                    << MRI->getRegClass(Reg)->getName() << '\n');
1782       ++NumInflated;
1783     }
1784   }
1785
1786   DEBUG(dump());
1787   DEBUG(LDV->dump());
1788   if (VerifyCoalescing)
1789     MF->verify(this, "After register coalescing");
1790   return true;
1791 }
1792
1793 /// print - Implement the dump method.
1794 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {
1795    LIS->print(O, m);
1796 }