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