Fix -join-splitedges: my previous "cleanup" broke it.
[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 "VirtRegMap.h"
20
21 #include "llvm/Pass.h"
22 #include "llvm/Value.h"
23 #include "llvm/ADT/OwningPtr.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
29 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
30 #include "llvm/CodeGen/LiveRangeEdit.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineLoopInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/Passes.h"
38 #include "llvm/CodeGen/RegisterClassInfo.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 "llvm/Target/TargetSubtargetInfo.h"
49 #include <algorithm>
50 #include <cmath>
51 using namespace llvm;
52
53 STATISTIC(numJoins    , "Number of interval joins performed");
54 STATISTIC(numCrossRCs , "Number of cross class joins performed");
55 STATISTIC(numCommutes , "Number of instruction commuting performed");
56 STATISTIC(numExtends  , "Number of copies extended");
57 STATISTIC(NumReMats   , "Number of instructions re-materialized");
58 STATISTIC(NumInflated , "Number of register classes inflated");
59 STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested");
60 STATISTIC(NumLaneResolves,  "Number of dead lane conflicts resolved");
61
62 static cl::opt<bool>
63 EnableJoining("join-liveintervals",
64               cl::desc("Coalesce copies (default=true)"),
65               cl::init(true));
66
67 // Temporary flag to test critical edge unsplitting.
68 static cl::opt<cl::boolOrDefault>
69 EnableJoinSplits("join-splitedges",
70   cl::desc("Coalesce copies on split edges (default=subtarget)"),
71   cl::init(cl::BOU_UNSET), cl::Hidden);
72
73 // Temporary flag to test global copy optimization.
74 static cl::opt<cl::boolOrDefault>
75 EnableGlobalCopies("join-globalcopies",
76   cl::desc("Coalesce copies that span blocks (default=subtarget)"),
77   cl::init(cl::BOU_UNSET), cl::Hidden);
78
79 static cl::opt<bool>
80 VerifyCoalescing("verify-coalescing",
81          cl::desc("Verify machine instrs before and after register coalescing"),
82          cl::Hidden);
83
84 namespace {
85   class RegisterCoalescer : public MachineFunctionPass,
86                             private LiveRangeEdit::Delegate {
87     MachineFunction* MF;
88     MachineRegisterInfo* MRI;
89     const TargetMachine* TM;
90     const TargetRegisterInfo* TRI;
91     const TargetInstrInfo* TII;
92     LiveIntervals *LIS;
93     LiveDebugVariables *LDV;
94     const MachineLoopInfo* Loops;
95     AliasAnalysis *AA;
96     RegisterClassInfo RegClassInfo;
97
98     /// \brief True if the coalescer should aggressively coalesce global copies
99     /// in favor of keeping local copies.
100     bool JoinGlobalCopies;
101
102     /// \brief True if the coalescer should aggressively coalesce fall-thru
103     /// blocks exclusively containing copies.
104     bool JoinSplitEdges;
105
106     /// WorkList - Copy instructions yet to be coalesced.
107     SmallVector<MachineInstr*, 8> WorkList;
108     SmallVector<MachineInstr*, 8> LocalWorkList;
109
110     /// ErasedInstrs - Set of instruction pointers that have been erased, and
111     /// that may be present in WorkList.
112     SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
113
114     /// Dead instructions that are about to be deleted.
115     SmallVector<MachineInstr*, 8> DeadDefs;
116
117     /// Virtual registers to be considered for register class inflation.
118     SmallVector<unsigned, 8> InflateRegs;
119
120     /// Recursively eliminate dead defs in DeadDefs.
121     void eliminateDeadDefs();
122
123     /// LiveRangeEdit callback.
124     void LRE_WillEraseInstruction(MachineInstr *MI);
125
126     /// coalesceLocals - coalesce the LocalWorkList.
127     void coalesceLocals();
128
129     /// joinAllIntervals - join compatible live intervals
130     void joinAllIntervals();
131
132     /// copyCoalesceInMBB - Coalesce copies in the specified MBB, putting
133     /// copies that cannot yet be coalesced into WorkList.
134     void copyCoalesceInMBB(MachineBasicBlock *MBB);
135
136     /// copyCoalesceWorkList - Try to coalesce all copies in CurrList. Return
137     /// true if any progress was made.
138     bool copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList);
139
140     /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
141     /// which are the src/dst of the copy instruction CopyMI.  This returns
142     /// true if the copy was successfully coalesced away. If it is not
143     /// currently possible to coalesce this interval, but it may be possible if
144     /// other things get coalesced, then it returns true by reference in
145     /// 'Again'.
146     bool joinCopy(MachineInstr *TheCopy, bool &Again);
147
148     /// joinIntervals - Attempt to join these two intervals.  On failure, this
149     /// returns false.  The output "SrcInt" will not have been modified, so we
150     /// can use this information below to update aliases.
151     bool joinIntervals(CoalescerPair &CP);
152
153     /// Attempt joining two virtual registers. Return true on success.
154     bool joinVirtRegs(CoalescerPair &CP);
155
156     /// Attempt joining with a reserved physreg.
157     bool joinReservedPhysReg(CoalescerPair &CP);
158
159     /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
160     /// the source value number is defined by a copy from the destination reg
161     /// see if we can merge these two destination reg valno# into a single
162     /// value number, eliminating a copy.
163     bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
164
165     /// hasOtherReachingDefs - Return true if there are definitions of IntB
166     /// other than BValNo val# that can reach uses of AValno val# of IntA.
167     bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
168                               VNInfo *AValNo, VNInfo *BValNo);
169
170     /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy.
171     /// If the source value number is defined by a commutable instruction and
172     /// its other operand is coalesced to the copy dest register, see if we
173     /// can transform the copy into a noop by commuting the definition.
174     bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
175
176     /// reMaterializeTrivialDef - If the source of a copy is defined by a
177     /// trivial computation, replace the copy by rematerialize the definition.
178     bool reMaterializeTrivialDef(LiveInterval &SrcInt, unsigned DstReg,
179                                  MachineInstr *CopyMI);
180
181     /// canJoinPhys - Return true if a physreg copy should be joined.
182     bool canJoinPhys(CoalescerPair &CP);
183
184     /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
185     /// update the subregister number if it is not zero. If DstReg is a
186     /// physical register and the existing subregister number of the def / use
187     /// being updated is not zero, make sure to set it to the correct physical
188     /// subregister.
189     void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
190
191     /// eliminateUndefCopy - Handle copies of undef values.
192     bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
193
194   public:
195     static char ID; // Class identification, replacement for typeinfo
196     RegisterCoalescer() : MachineFunctionPass(ID) {
197       initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
198     }
199
200     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
201
202     virtual void releaseMemory();
203
204     /// runOnMachineFunction - pass entry point
205     virtual bool runOnMachineFunction(MachineFunction&);
206
207     /// print - Implement the dump method.
208     virtual void print(raw_ostream &O, const Module* = 0) const;
209   };
210 } /// end anonymous namespace
211
212 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
213
214 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
215                       "Simple Register Coalescing", false, false)
216 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
217 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
218 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
219 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
220 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
221 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
222                     "Simple Register Coalescing", false, false)
223
224 char RegisterCoalescer::ID = 0;
225
226 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
227                         unsigned &Src, unsigned &Dst,
228                         unsigned &SrcSub, unsigned &DstSub) {
229   if (MI->isCopy()) {
230     Dst = MI->getOperand(0).getReg();
231     DstSub = MI->getOperand(0).getSubReg();
232     Src = MI->getOperand(1).getReg();
233     SrcSub = MI->getOperand(1).getSubReg();
234   } else if (MI->isSubregToReg()) {
235     Dst = MI->getOperand(0).getReg();
236     DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
237                                       MI->getOperand(3).getImm());
238     Src = MI->getOperand(2).getReg();
239     SrcSub = MI->getOperand(2).getSubReg();
240   } else
241     return false;
242   return true;
243 }
244
245 // Return true if this block should be vacated by the coalescer to eliminate
246 // branches. The important cases to handle in the coalescer are critical edges
247 // split during phi elimination which contain only copies. Simple blocks that
248 // contain non-branches should also be vacated, but this can be handled by an
249 // earlier pass similar to early if-conversion.
250 static bool isSplitEdge(const MachineBasicBlock *MBB) {
251   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
252     return false;
253
254   for (MachineBasicBlock::const_iterator MII = MBB->begin(), E = MBB->end();
255        MII != E; ++MII) {
256     if (!MII->isCopyLike() && !MII->isUnconditionalBranch())
257       return false;
258   }
259   return true;
260 }
261
262 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
263   SrcReg = DstReg = 0;
264   SrcIdx = DstIdx = 0;
265   NewRC = 0;
266   Flipped = CrossClass = false;
267
268   unsigned Src, Dst, SrcSub, DstSub;
269   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
270     return false;
271   Partial = SrcSub || DstSub;
272
273   // If one register is a physreg, it must be Dst.
274   if (TargetRegisterInfo::isPhysicalRegister(Src)) {
275     if (TargetRegisterInfo::isPhysicalRegister(Dst))
276       return false;
277     std::swap(Src, Dst);
278     std::swap(SrcSub, DstSub);
279     Flipped = true;
280   }
281
282   const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
283
284   if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
285     // Eliminate DstSub on a physreg.
286     if (DstSub) {
287       Dst = TRI.getSubReg(Dst, DstSub);
288       if (!Dst) return false;
289       DstSub = 0;
290     }
291
292     // Eliminate SrcSub by picking a corresponding Dst superregister.
293     if (SrcSub) {
294       Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
295       if (!Dst) return false;
296       SrcSub = 0;
297     } else if (!MRI.getRegClass(Src)->contains(Dst)) {
298       return false;
299     }
300   } else {
301     // Both registers are virtual.
302     const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
303     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
304
305     // Both registers have subreg indices.
306     if (SrcSub && DstSub) {
307       // Copies between different sub-registers are never coalescable.
308       if (Src == Dst && SrcSub != DstSub)
309         return false;
310
311       NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
312                                          SrcIdx, DstIdx);
313       if (!NewRC)
314         return false;
315     } else if (DstSub) {
316       // SrcReg will be merged with a sub-register of DstReg.
317       SrcIdx = DstSub;
318       NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
319     } else if (SrcSub) {
320       // DstReg will be merged with a sub-register of SrcReg.
321       DstIdx = SrcSub;
322       NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
323     } else {
324       // This is a straight copy without sub-registers.
325       NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
326     }
327
328     // The combined constraint may be impossible to satisfy.
329     if (!NewRC)
330       return false;
331
332     // Prefer SrcReg to be a sub-register of DstReg.
333     // FIXME: Coalescer should support subregs symmetrically.
334     if (DstIdx && !SrcIdx) {
335       std::swap(Src, Dst);
336       std::swap(SrcIdx, DstIdx);
337       Flipped = !Flipped;
338     }
339
340     CrossClass = NewRC != DstRC || NewRC != SrcRC;
341   }
342   // Check our invariants
343   assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
344   assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
345          "Cannot have a physical SubIdx");
346   SrcReg = Src;
347   DstReg = Dst;
348   return true;
349 }
350
351 bool CoalescerPair::flip() {
352   if (TargetRegisterInfo::isPhysicalRegister(DstReg))
353     return false;
354   std::swap(SrcReg, DstReg);
355   std::swap(SrcIdx, DstIdx);
356   Flipped = !Flipped;
357   return true;
358 }
359
360 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
361   if (!MI)
362     return false;
363   unsigned Src, Dst, SrcSub, DstSub;
364   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
365     return false;
366
367   // Find the virtual register that is SrcReg.
368   if (Dst == SrcReg) {
369     std::swap(Src, Dst);
370     std::swap(SrcSub, DstSub);
371   } else if (Src != SrcReg) {
372     return false;
373   }
374
375   // Now check that Dst matches DstReg.
376   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
377     if (!TargetRegisterInfo::isPhysicalRegister(Dst))
378       return false;
379     assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
380     // DstSub could be set for a physreg from INSERT_SUBREG.
381     if (DstSub)
382       Dst = TRI.getSubReg(Dst, DstSub);
383     // Full copy of Src.
384     if (!SrcSub)
385       return DstReg == Dst;
386     // This is a partial register copy. Check that the parts match.
387     return TRI.getSubReg(DstReg, SrcSub) == Dst;
388   } else {
389     // DstReg is virtual.
390     if (DstReg != Dst)
391       return false;
392     // Registers match, do the subregisters line up?
393     return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
394            TRI.composeSubRegIndices(DstIdx, DstSub);
395   }
396 }
397
398 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
399   AU.setPreservesCFG();
400   AU.addRequired<AliasAnalysis>();
401   AU.addRequired<LiveIntervals>();
402   AU.addPreserved<LiveIntervals>();
403   AU.addRequired<LiveDebugVariables>();
404   AU.addPreserved<LiveDebugVariables>();
405   AU.addPreserved<SlotIndexes>();
406   AU.addRequired<MachineLoopInfo>();
407   AU.addPreserved<MachineLoopInfo>();
408   AU.addPreservedID(MachineDominatorsID);
409   MachineFunctionPass::getAnalysisUsage(AU);
410 }
411
412 void RegisterCoalescer::eliminateDeadDefs() {
413   SmallVector<LiveInterval*, 8> NewRegs;
414   LiveRangeEdit(0, NewRegs, *MF, *LIS, 0, this).eliminateDeadDefs(DeadDefs);
415 }
416
417 // Callback from eliminateDeadDefs().
418 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
419   // MI may be in WorkList. Make sure we don't visit it.
420   ErasedInstrs.insert(MI);
421 }
422
423 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
424 /// being the source and IntB being the dest, thus this defines a value number
425 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
426 /// see if we can merge these two pieces of B into a single value number,
427 /// eliminating a copy.  For example:
428 ///
429 ///  A3 = B0
430 ///    ...
431 ///  B1 = A3      <- this copy
432 ///
433 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
434 /// value number to be replaced with B0 (which simplifies the B liveinterval).
435 ///
436 /// This returns true if an interval was modified.
437 ///
438 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
439                                              MachineInstr *CopyMI) {
440   assert(!CP.isPartial() && "This doesn't work for partial copies.");
441   assert(!CP.isPhys() && "This doesn't work for physreg copies.");
442
443   LiveInterval &IntA =
444     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
445   LiveInterval &IntB =
446     LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
447   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
448
449   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
450   // the example above.
451   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
452   if (BLR == IntB.end()) return false;
453   VNInfo *BValNo = BLR->valno;
454
455   // Get the location that B is defined at.  Two options: either this value has
456   // an unknown definition point or it is defined at CopyIdx.  If unknown, we
457   // can't process it.
458   if (BValNo->def != CopyIdx) return false;
459
460   // AValNo is the value number in A that defines the copy, A3 in the example.
461   SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
462   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
463   // The live range might not exist after fun with physreg coalescing.
464   if (ALR == IntA.end()) return false;
465   VNInfo *AValNo = ALR->valno;
466
467   // If AValNo is defined as a copy from IntB, we can potentially process this.
468   // Get the instruction that defines this value number.
469   MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
470   // Don't allow any partial copies, even if isCoalescable() allows them.
471   if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
472     return false;
473
474   // Get the LiveRange in IntB that this value number starts with.
475   LiveInterval::iterator ValLR =
476     IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
477   if (ValLR == IntB.end())
478     return false;
479
480   // Make sure that the end of the live range is inside the same block as
481   // CopyMI.
482   MachineInstr *ValLREndInst =
483     LIS->getInstructionFromIndex(ValLR->end.getPrevSlot());
484   if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
485     return false;
486
487   // Okay, we now know that ValLR ends in the same block that the CopyMI
488   // live-range starts.  If there are no intervening live ranges between them in
489   // IntB, we can merge them.
490   if (ValLR+1 != BLR) return false;
491
492   DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI));
493
494   SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
495   // We are about to delete CopyMI, so need to remove it as the 'instruction
496   // that defines this value #'. Update the valnum with the new defining
497   // instruction #.
498   BValNo->def = FillerStart;
499
500   // Okay, we can merge them.  We need to insert a new liverange:
501   // [ValLR.end, BLR.begin) of either value number, then we merge the
502   // two value numbers.
503   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
504
505   // Okay, merge "B1" into the same value number as "B0".
506   if (BValNo != ValLR->valno)
507     IntB.MergeValueNumberInto(BValNo, ValLR->valno);
508   DEBUG(dbgs() << "   result = " << IntB << '\n');
509
510   // If the source instruction was killing the source register before the
511   // merge, unset the isKill marker given the live range has been extended.
512   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
513   if (UIdx != -1) {
514     ValLREndInst->getOperand(UIdx).setIsKill(false);
515   }
516
517   // Rewrite the copy. If the copy instruction was killing the destination
518   // register before the merge, find the last use and trim the live range. That
519   // will also add the isKill marker.
520   CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
521   if (ALR->end == CopyIdx)
522     LIS->shrinkToUses(&IntA);
523
524   ++numExtends;
525   return true;
526 }
527
528 /// hasOtherReachingDefs - Return true if there are definitions of IntB
529 /// other than BValNo val# that can reach uses of AValno val# of IntA.
530 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
531                                              LiveInterval &IntB,
532                                              VNInfo *AValNo,
533                                              VNInfo *BValNo) {
534   // If AValNo has PHI kills, conservatively assume that IntB defs can reach
535   // the PHI values.
536   if (LIS->hasPHIKill(IntA, AValNo))
537     return true;
538
539   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
540        AI != AE; ++AI) {
541     if (AI->valno != AValNo) continue;
542     LiveInterval::Ranges::iterator BI =
543       std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
544     if (BI != IntB.ranges.begin())
545       --BI;
546     for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
547       if (BI->valno == BValNo)
548         continue;
549       if (BI->start <= AI->start && BI->end > AI->start)
550         return true;
551       if (BI->start > AI->start && BI->start < AI->end)
552         return true;
553     }
554   }
555   return false;
556 }
557
558 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy with
559 /// IntA being the source and IntB being the dest, thus this defines a value
560 /// number in IntB.  If the source value number (in IntA) is defined by a
561 /// commutable instruction and its other operand is coalesced to the copy dest
562 /// register, see if we can transform the copy into a noop by commuting the
563 /// definition. For example,
564 ///
565 ///  A3 = op A2 B0<kill>
566 ///    ...
567 ///  B1 = A3      <- this copy
568 ///    ...
569 ///     = op A3   <- more uses
570 ///
571 /// ==>
572 ///
573 ///  B2 = op B0 A2<kill>
574 ///    ...
575 ///  B1 = B2      <- now an identify copy
576 ///    ...
577 ///     = op B2   <- more uses
578 ///
579 /// This returns true if an interval was modified.
580 ///
581 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
582                                                  MachineInstr *CopyMI) {
583   assert (!CP.isPhys());
584
585   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
586
587   LiveInterval &IntA =
588     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
589   LiveInterval &IntB =
590     LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
591
592   // BValNo is a value number in B that is defined by a copy from A. 'B3' in
593   // the example above.
594   VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
595   if (!BValNo || BValNo->def != CopyIdx)
596     return false;
597
598   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
599
600   // AValNo is the value number in A that defines the copy, A3 in the example.
601   VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
602   assert(AValNo && "COPY source not live");
603   if (AValNo->isPHIDef() || AValNo->isUnused())
604     return false;
605   MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
606   if (!DefMI)
607     return false;
608   if (!DefMI->isCommutable())
609     return false;
610   // If DefMI is a two-address instruction then commuting it will change the
611   // destination register.
612   int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
613   assert(DefIdx != -1);
614   unsigned UseOpIdx;
615   if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
616     return false;
617   unsigned Op1, Op2, NewDstIdx;
618   if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
619     return false;
620   if (Op1 == UseOpIdx)
621     NewDstIdx = Op2;
622   else if (Op2 == UseOpIdx)
623     NewDstIdx = Op1;
624   else
625     return false;
626
627   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
628   unsigned NewReg = NewDstMO.getReg();
629   if (NewReg != IntB.reg || !LiveRangeQuery(IntB, AValNo->def).isKill())
630     return false;
631
632   // Make sure there are no other definitions of IntB that would reach the
633   // uses which the new definition can reach.
634   if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
635     return false;
636
637   // If some of the uses of IntA.reg is already coalesced away, return false.
638   // It's not possible to determine whether it's safe to perform the coalescing.
639   for (MachineRegisterInfo::use_nodbg_iterator UI =
640          MRI->use_nodbg_begin(IntA.reg),
641        UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
642     MachineInstr *UseMI = &*UI;
643     SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
644     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
645     if (ULR == IntA.end() || ULR->valno != AValNo)
646       continue;
647     // If this use is tied to a def, we can't rewrite the register.
648     if (UseMI->isRegTiedToDefOperand(UI.getOperandNo()))
649       return false;
650   }
651
652   DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
653                << *DefMI);
654
655   // At this point we have decided that it is legal to do this
656   // transformation.  Start by commuting the instruction.
657   MachineBasicBlock *MBB = DefMI->getParent();
658   MachineInstr *NewMI = TII->commuteInstruction(DefMI);
659   if (!NewMI)
660     return false;
661   if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
662       TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
663       !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
664     return false;
665   if (NewMI != DefMI) {
666     LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
667     MachineBasicBlock::iterator Pos = DefMI;
668     MBB->insert(Pos, NewMI);
669     MBB->erase(DefMI);
670   }
671   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
672   NewMI->getOperand(OpIdx).setIsKill();
673
674   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
675   // A = or A, B
676   // ...
677   // B = A
678   // ...
679   // C = A<kill>
680   // ...
681   //   = B
682
683   // Update uses of IntA of the specific Val# with IntB.
684   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
685          UE = MRI->use_end(); UI != UE;) {
686     MachineOperand &UseMO = UI.getOperand();
687     MachineInstr *UseMI = &*UI;
688     ++UI;
689     if (UseMI->isDebugValue()) {
690       // FIXME These don't have an instruction index.  Not clear we have enough
691       // info to decide whether to do this replacement or not.  For now do it.
692       UseMO.setReg(NewReg);
693       continue;
694     }
695     SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
696     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
697     if (ULR == IntA.end() || ULR->valno != AValNo)
698       continue;
699     // Kill flags are no longer accurate. They are recomputed after RA.
700     UseMO.setIsKill(false);
701     if (TargetRegisterInfo::isPhysicalRegister(NewReg))
702       UseMO.substPhysReg(NewReg, *TRI);
703     else
704       UseMO.setReg(NewReg);
705     if (UseMI == CopyMI)
706       continue;
707     if (!UseMI->isCopy())
708       continue;
709     if (UseMI->getOperand(0).getReg() != IntB.reg ||
710         UseMI->getOperand(0).getSubReg())
711       continue;
712
713     // This copy will become a noop. If it's defining a new val#, merge it into
714     // BValNo.
715     SlotIndex DefIdx = UseIdx.getRegSlot();
716     VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
717     if (!DVNI)
718       continue;
719     DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
720     assert(DVNI->def == DefIdx);
721     BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
722     ErasedInstrs.insert(UseMI);
723     LIS->RemoveMachineInstrFromMaps(UseMI);
724     UseMI->eraseFromParent();
725   }
726
727   // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
728   // is updated.
729   VNInfo *ValNo = BValNo;
730   ValNo->def = AValNo->def;
731   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
732        AI != AE; ++AI) {
733     if (AI->valno != AValNo) continue;
734     IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
735   }
736   DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
737
738   IntA.removeValNo(AValNo);
739   DEBUG(dbgs() << "\t\ttrimmed:  " << IntA << '\n');
740   ++numCommutes;
741   return true;
742 }
743
744 /// reMaterializeTrivialDef - If the source of a copy is defined by a trivial
745 /// computation, replace the copy by rematerialize the definition.
746 bool RegisterCoalescer::reMaterializeTrivialDef(LiveInterval &SrcInt,
747                                                 unsigned DstReg,
748                                                 MachineInstr *CopyMI) {
749   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
750   LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
751   assert(SrcLR != SrcInt.end() && "Live range not found!");
752   VNInfo *ValNo = SrcLR->valno;
753   if (ValNo->isPHIDef() || ValNo->isUnused())
754     return false;
755   MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
756   if (!DefMI)
757     return false;
758   assert(DefMI && "Defining instruction disappeared");
759   if (!DefMI->isAsCheapAsAMove())
760     return false;
761   if (!TII->isTriviallyReMaterializable(DefMI, AA))
762     return false;
763   bool SawStore = false;
764   if (!DefMI->isSafeToMove(TII, AA, SawStore))
765     return false;
766   const MCInstrDesc &MCID = DefMI->getDesc();
767   if (MCID.getNumDefs() != 1)
768     return false;
769   if (!DefMI->isImplicitDef()) {
770     // Make sure the copy destination register class fits the instruction
771     // definition register class. The mismatch can happen as a result of earlier
772     // extract_subreg, insert_subreg, subreg_to_reg coalescing.
773     const TargetRegisterClass *RC = TII->getRegClass(MCID, 0, TRI, *MF);
774     if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
775       if (MRI->getRegClass(DstReg) != RC)
776         return false;
777     } else if (!RC->contains(DstReg))
778       return false;
779   }
780
781   MachineBasicBlock *MBB = CopyMI->getParent();
782   MachineBasicBlock::iterator MII =
783     llvm::next(MachineBasicBlock::iterator(CopyMI));
784   TII->reMaterialize(*MBB, MII, DstReg, 0, DefMI, *TRI);
785   MachineInstr *NewMI = prior(MII);
786
787   // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
788   // We need to remember these so we can add intervals once we insert
789   // NewMI into SlotIndexes.
790   SmallVector<unsigned, 4> NewMIImplDefs;
791   for (unsigned i = NewMI->getDesc().getNumOperands(),
792          e = NewMI->getNumOperands(); i != e; ++i) {
793     MachineOperand &MO = NewMI->getOperand(i);
794     if (MO.isReg()) {
795       assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
796              TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
797       NewMIImplDefs.push_back(MO.getReg());
798     }
799   }
800
801   // CopyMI may have implicit operands, transfer them over to the newly
802   // rematerialized instruction. And update implicit def interval valnos.
803   for (unsigned i = CopyMI->getDesc().getNumOperands(),
804          e = CopyMI->getNumOperands(); i != e; ++i) {
805     MachineOperand &MO = CopyMI->getOperand(i);
806     if (MO.isReg()) {
807       assert(MO.isImplicit() && "No explicit operands after implict operands.");
808       // Discard VReg implicit defs.
809       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
810         NewMI->addOperand(MO);
811       }
812     }
813   }
814
815   LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
816
817   SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
818   for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
819     unsigned Reg = NewMIImplDefs[i];
820     for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
821       if (LiveInterval *LI = LIS->getCachedRegUnit(*Units))
822         LI->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
823   }
824
825   CopyMI->eraseFromParent();
826   ErasedInstrs.insert(CopyMI);
827   DEBUG(dbgs() << "Remat: " << *NewMI);
828   ++NumReMats;
829
830   // The source interval can become smaller because we removed a use.
831   LIS->shrinkToUses(&SrcInt, &DeadDefs);
832   if (!DeadDefs.empty())
833     eliminateDeadDefs();
834
835   return true;
836 }
837
838 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
839 /// values, it only removes local variables. When we have a copy like:
840 ///
841 ///   %vreg1 = COPY %vreg2<undef>
842 ///
843 /// We delete the copy and remove the corresponding value number from %vreg1.
844 /// Any uses of that value number are marked as <undef>.
845 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
846                                            const CoalescerPair &CP) {
847   SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
848   LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
849   if (SrcInt->liveAt(Idx))
850     return false;
851   LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
852   if (DstInt->liveAt(Idx))
853     return false;
854
855   // No intervals are live-in to CopyMI - it is undef.
856   if (CP.isFlipped())
857     DstInt = SrcInt;
858   SrcInt = 0;
859
860   VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
861   assert(DeadVNI && "No value defined in DstInt");
862   DstInt->removeValNo(DeadVNI);
863
864   // Find new undef uses.
865   for (MachineRegisterInfo::reg_nodbg_iterator
866          I = MRI->reg_nodbg_begin(DstInt->reg), E = MRI->reg_nodbg_end();
867        I != E; ++I) {
868     MachineOperand &MO = I.getOperand();
869     if (MO.isDef() || MO.isUndef())
870       continue;
871     MachineInstr *MI = MO.getParent();
872     SlotIndex Idx = LIS->getInstructionIndex(MI);
873     if (DstInt->liveAt(Idx))
874       continue;
875     MO.setIsUndef(true);
876     DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
877   }
878   return true;
879 }
880
881 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
882 /// update the subregister number if it is not zero. If DstReg is a
883 /// physical register and the existing subregister number of the def / use
884 /// being updated is not zero, make sure to set it to the correct physical
885 /// subregister.
886 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
887                                           unsigned DstReg,
888                                           unsigned SubIdx) {
889   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
890   LiveInterval *DstInt = DstIsPhys ? 0 : &LIS->getInterval(DstReg);
891
892   // Update LiveDebugVariables.
893   LDV->renameRegister(SrcReg, DstReg, SubIdx);
894
895   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg);
896        MachineInstr *UseMI = I.skipInstruction();) {
897     SmallVector<unsigned,8> Ops;
898     bool Reads, Writes;
899     tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
900
901     // If SrcReg wasn't read, it may still be the case that DstReg is live-in
902     // because SrcReg is a sub-register.
903     if (DstInt && !Reads && SubIdx)
904       Reads = DstInt->liveAt(LIS->getInstructionIndex(UseMI));
905
906     // Replace SrcReg with DstReg in all UseMI operands.
907     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
908       MachineOperand &MO = UseMI->getOperand(Ops[i]);
909
910       // Adjust <undef> flags in case of sub-register joins. We don't want to
911       // turn a full def into a read-modify-write sub-register def and vice
912       // versa.
913       if (SubIdx && MO.isDef())
914         MO.setIsUndef(!Reads);
915
916       if (DstIsPhys)
917         MO.substPhysReg(DstReg, *TRI);
918       else
919         MO.substVirtReg(DstReg, SubIdx, *TRI);
920     }
921
922     DEBUG({
923         dbgs() << "\t\tupdated: ";
924         if (!UseMI->isDebugValue())
925           dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
926         dbgs() << *UseMI;
927       });
928   }
929 }
930
931 /// canJoinPhys - Return true if a copy involving a physreg should be joined.
932 bool RegisterCoalescer::canJoinPhys(CoalescerPair &CP) {
933   /// Always join simple intervals that are defined by a single copy from a
934   /// reserved register. This doesn't increase register pressure, so it is
935   /// always beneficial.
936   if (!MRI->isReserved(CP.getDstReg())) {
937     DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
938     return false;
939   }
940
941   LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
942   if (CP.isFlipped() && JoinVInt.containsOneValue())
943     return true;
944
945   DEBUG(dbgs() << "\tCannot join defs into reserved register.\n");
946   return false;
947 }
948
949 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
950 /// which are the src/dst of the copy instruction CopyMI.  This returns true
951 /// if the copy was successfully coalesced away. If it is not currently
952 /// possible to coalesce this interval, but it may be possible if other
953 /// things get coalesced, then it returns true by reference in 'Again'.
954 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
955
956   Again = false;
957   DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
958
959   CoalescerPair CP(*TRI);
960   if (!CP.setRegisters(CopyMI)) {
961     DEBUG(dbgs() << "\tNot coalescable.\n");
962     return false;
963   }
964
965   // Dead code elimination. This really should be handled by MachineDCE, but
966   // sometimes dead copies slip through, and we can't generate invalid live
967   // ranges.
968   if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
969     DEBUG(dbgs() << "\tCopy is dead.\n");
970     DeadDefs.push_back(CopyMI);
971     eliminateDeadDefs();
972     return true;
973   }
974
975   // Eliminate undefs.
976   if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
977     DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
978     LIS->RemoveMachineInstrFromMaps(CopyMI);
979     CopyMI->eraseFromParent();
980     return false;  // Not coalescable.
981   }
982
983   // Coalesced copies are normally removed immediately, but transformations
984   // like removeCopyByCommutingDef() can inadvertently create identity copies.
985   // When that happens, just join the values and remove the copy.
986   if (CP.getSrcReg() == CP.getDstReg()) {
987     LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
988     DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
989     LiveRangeQuery LRQ(LI, LIS->getInstructionIndex(CopyMI));
990     if (VNInfo *DefVNI = LRQ.valueDefined()) {
991       VNInfo *ReadVNI = LRQ.valueIn();
992       assert(ReadVNI && "No value before copy and no <undef> flag.");
993       assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
994       LI.MergeValueNumberInto(DefVNI, ReadVNI);
995       DEBUG(dbgs() << "\tMerged values:          " << LI << '\n');
996     }
997     LIS->RemoveMachineInstrFromMaps(CopyMI);
998     CopyMI->eraseFromParent();
999     return true;
1000   }
1001
1002   // Enforce policies.
1003   if (CP.isPhys()) {
1004     DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1005                  << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
1006                  << '\n');
1007     if (!canJoinPhys(CP)) {
1008       // Before giving up coalescing, if definition of source is defined by
1009       // trivial computation, try rematerializing it.
1010       if (!CP.isFlipped() &&
1011           reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()),
1012                                   CP.getDstReg(), CopyMI))
1013         return true;
1014       return false;
1015     }
1016   } else {
1017     DEBUG({
1018       dbgs() << "\tConsidering merging to " << CP.getNewRC()->getName()
1019              << " with ";
1020       if (CP.getDstIdx() && CP.getSrcIdx())
1021         dbgs() << PrintReg(CP.getDstReg()) << " in "
1022                << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
1023                << PrintReg(CP.getSrcReg()) << " in "
1024                << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
1025       else
1026         dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
1027                << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
1028     });
1029
1030     // When possible, let DstReg be the larger interval.
1031     if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).ranges.size() >
1032                            LIS->getInterval(CP.getDstReg()).ranges.size())
1033       CP.flip();
1034   }
1035
1036   // Okay, attempt to join these two intervals.  On failure, this returns false.
1037   // Otherwise, if one of the intervals being joined is a physreg, this method
1038   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1039   // been modified, so we can use this information below to update aliases.
1040   if (!joinIntervals(CP)) {
1041     // Coalescing failed.
1042
1043     // If definition of source is defined by trivial computation, try
1044     // rematerializing it.
1045     if (!CP.isFlipped() &&
1046         reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()),
1047                                 CP.getDstReg(), CopyMI))
1048       return true;
1049
1050     // If we can eliminate the copy without merging the live ranges, do so now.
1051     if (!CP.isPartial() && !CP.isPhys()) {
1052       if (adjustCopiesBackFrom(CP, CopyMI) ||
1053           removeCopyByCommutingDef(CP, CopyMI)) {
1054         LIS->RemoveMachineInstrFromMaps(CopyMI);
1055         CopyMI->eraseFromParent();
1056         DEBUG(dbgs() << "\tTrivial!\n");
1057         return true;
1058       }
1059     }
1060
1061     // Otherwise, we are unable to join the intervals.
1062     DEBUG(dbgs() << "\tInterference!\n");
1063     Again = true;  // May be possible to coalesce later.
1064     return false;
1065   }
1066
1067   // Coalescing to a virtual register that is of a sub-register class of the
1068   // other. Make sure the resulting register is set to the right register class.
1069   if (CP.isCrossClass()) {
1070     ++numCrossRCs;
1071     MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1072   }
1073
1074   // Removing sub-register copies can ease the register class constraints.
1075   // Make sure we attempt to inflate the register class of DstReg.
1076   if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
1077     InflateRegs.push_back(CP.getDstReg());
1078
1079   // CopyMI has been erased by joinIntervals at this point. Remove it from
1080   // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
1081   // to the work list. This keeps ErasedInstrs from growing needlessly.
1082   ErasedInstrs.erase(CopyMI);
1083
1084   // Rewrite all SrcReg operands to DstReg.
1085   // Also update DstReg operands to include DstIdx if it is set.
1086   if (CP.getDstIdx())
1087     updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1088   updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1089
1090   // SrcReg is guaranteed to be the register whose live interval that is
1091   // being merged.
1092   LIS->removeInterval(CP.getSrcReg());
1093
1094   // Update regalloc hint.
1095   TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1096
1097   DEBUG({
1098     dbgs() << "\tJoined. Result = " << PrintReg(CP.getDstReg(), TRI);
1099     if (!CP.isPhys())
1100       dbgs() << LIS->getInterval(CP.getDstReg());
1101      dbgs() << '\n';
1102   });
1103
1104   ++numJoins;
1105   return true;
1106 }
1107
1108 /// Attempt joining with a reserved physreg.
1109 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1110   assert(CP.isPhys() && "Must be a physreg copy");
1111   assert(MRI->isReserved(CP.getDstReg()) && "Not a reserved register");
1112   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1113   DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1114                << '\n');
1115
1116   assert(CP.isFlipped() && RHS.containsOneValue() &&
1117          "Invalid join with reserved register");
1118
1119   // Optimization for reserved registers like ESP. We can only merge with a
1120   // reserved physreg if RHS has a single value that is a copy of CP.DstReg().
1121   // The live range of the reserved register will look like a set of dead defs
1122   // - we don't properly track the live range of reserved registers.
1123
1124   // Deny any overlapping intervals.  This depends on all the reserved
1125   // register live ranges to look like dead defs.
1126   for (MCRegUnitIterator UI(CP.getDstReg(), TRI); UI.isValid(); ++UI)
1127     if (RHS.overlaps(LIS->getRegUnit(*UI))) {
1128       DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n');
1129       return false;
1130     }
1131
1132   // Skip any value computations, we are not adding new values to the
1133   // reserved register.  Also skip merging the live ranges, the reserved
1134   // register live range doesn't need to be accurate as long as all the
1135   // defs are there.
1136
1137   // Delete the identity copy.
1138   MachineInstr *CopyMI = MRI->getVRegDef(RHS.reg);
1139   LIS->RemoveMachineInstrFromMaps(CopyMI);
1140   CopyMI->eraseFromParent();
1141
1142   // We don't track kills for reserved registers.
1143   MRI->clearKillFlags(CP.getSrcReg());
1144
1145   return true;
1146 }
1147
1148 //===----------------------------------------------------------------------===//
1149 //                 Interference checking and interval joining
1150 //===----------------------------------------------------------------------===//
1151 //
1152 // In the easiest case, the two live ranges being joined are disjoint, and
1153 // there is no interference to consider. It is quite common, though, to have
1154 // overlapping live ranges, and we need to check if the interference can be
1155 // resolved.
1156 //
1157 // The live range of a single SSA value forms a sub-tree of the dominator tree.
1158 // This means that two SSA values overlap if and only if the def of one value
1159 // is contained in the live range of the other value. As a special case, the
1160 // overlapping values can be defined at the same index.
1161 //
1162 // The interference from an overlapping def can be resolved in these cases:
1163 //
1164 // 1. Coalescable copies. The value is defined by a copy that would become an
1165 //    identity copy after joining SrcReg and DstReg. The copy instruction will
1166 //    be removed, and the value will be merged with the source value.
1167 //
1168 //    There can be several copies back and forth, causing many values to be
1169 //    merged into one. We compute a list of ultimate values in the joined live
1170 //    range as well as a mappings from the old value numbers.
1171 //
1172 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
1173 //    predecessors have a live out value. It doesn't cause real interference,
1174 //    and can be merged into the value it overlaps. Like a coalescable copy, it
1175 //    can be erased after joining.
1176 //
1177 // 3. Copy of external value. The overlapping def may be a copy of a value that
1178 //    is already in the other register. This is like a coalescable copy, but
1179 //    the live range of the source register must be trimmed after erasing the
1180 //    copy instruction:
1181 //
1182 //      %src = COPY %ext
1183 //      %dst = COPY %ext  <-- Remove this COPY, trim the live range of %ext.
1184 //
1185 // 4. Clobbering undefined lanes. Vector registers are sometimes built by
1186 //    defining one lane at a time:
1187 //
1188 //      %dst:ssub0<def,read-undef> = FOO
1189 //      %src = BAR
1190 //      %dst:ssub1<def> = COPY %src
1191 //
1192 //    The live range of %src overlaps the %dst value defined by FOO, but
1193 //    merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
1194 //    which was undef anyway.
1195 //
1196 //    The value mapping is more complicated in this case. The final live range
1197 //    will have different value numbers for both FOO and BAR, but there is no
1198 //    simple mapping from old to new values. It may even be necessary to add
1199 //    new PHI values.
1200 //
1201 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
1202 //    is live, but never read. This can happen because we don't compute
1203 //    individual live ranges per lane.
1204 //
1205 //      %dst<def> = FOO
1206 //      %src = BAR
1207 //      %dst:ssub1<def> = COPY %src
1208 //
1209 //    This kind of interference is only resolved locally. If the clobbered
1210 //    lane value escapes the block, the join is aborted.
1211
1212 namespace {
1213 /// Track information about values in a single virtual register about to be
1214 /// joined. Objects of this class are always created in pairs - one for each
1215 /// side of the CoalescerPair.
1216 class JoinVals {
1217   LiveInterval &LI;
1218
1219   // Location of this register in the final joined register.
1220   // Either CP.DstIdx or CP.SrcIdx.
1221   unsigned SubIdx;
1222
1223   // Values that will be present in the final live range.
1224   SmallVectorImpl<VNInfo*> &NewVNInfo;
1225
1226   const CoalescerPair &CP;
1227   LiveIntervals *LIS;
1228   SlotIndexes *Indexes;
1229   const TargetRegisterInfo *TRI;
1230
1231   // Value number assignments. Maps value numbers in LI to entries in NewVNInfo.
1232   // This is suitable for passing to LiveInterval::join().
1233   SmallVector<int, 8> Assignments;
1234
1235   // Conflict resolution for overlapping values.
1236   enum ConflictResolution {
1237     // No overlap, simply keep this value.
1238     CR_Keep,
1239
1240     // Merge this value into OtherVNI and erase the defining instruction.
1241     // Used for IMPLICIT_DEF, coalescable copies, and copies from external
1242     // values.
1243     CR_Erase,
1244
1245     // Merge this value into OtherVNI but keep the defining instruction.
1246     // This is for the special case where OtherVNI is defined by the same
1247     // instruction.
1248     CR_Merge,
1249
1250     // Keep this value, and have it replace OtherVNI where possible. This
1251     // complicates value mapping since OtherVNI maps to two different values
1252     // before and after this def.
1253     // Used when clobbering undefined or dead lanes.
1254     CR_Replace,
1255
1256     // Unresolved conflict. Visit later when all values have been mapped.
1257     CR_Unresolved,
1258
1259     // Unresolvable conflict. Abort the join.
1260     CR_Impossible
1261   };
1262
1263   // Per-value info for LI. The lane bit masks are all relative to the final
1264   // joined register, so they can be compared directly between SrcReg and
1265   // DstReg.
1266   struct Val {
1267     ConflictResolution Resolution;
1268
1269     // Lanes written by this def, 0 for unanalyzed values.
1270     unsigned WriteLanes;
1271
1272     // Lanes with defined values in this register. Other lanes are undef and
1273     // safe to clobber.
1274     unsigned ValidLanes;
1275
1276     // Value in LI being redefined by this def.
1277     VNInfo *RedefVNI;
1278
1279     // Value in the other live range that overlaps this def, if any.
1280     VNInfo *OtherVNI;
1281
1282     // Is this value an IMPLICIT_DEF?
1283     bool IsImplicitDef;
1284
1285     // True when the live range of this value will be pruned because of an
1286     // overlapping CR_Replace value in the other live range.
1287     bool Pruned;
1288
1289     // True once Pruned above has been computed.
1290     bool PrunedComputed;
1291
1292     Val() : Resolution(CR_Keep), WriteLanes(0), ValidLanes(0),
1293             RedefVNI(0), OtherVNI(0), IsImplicitDef(false), Pruned(false),
1294             PrunedComputed(false) {}
1295
1296     bool isAnalyzed() const { return WriteLanes != 0; }
1297   };
1298
1299   // One entry per value number in LI.
1300   SmallVector<Val, 8> Vals;
1301
1302   unsigned computeWriteLanes(const MachineInstr *DefMI, bool &Redef);
1303   VNInfo *stripCopies(VNInfo *VNI);
1304   ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
1305   void computeAssignment(unsigned ValNo, JoinVals &Other);
1306   bool taintExtent(unsigned, unsigned, JoinVals&,
1307                    SmallVectorImpl<std::pair<SlotIndex, unsigned> >&);
1308   bool usesLanes(MachineInstr *MI, unsigned, unsigned, unsigned);
1309   bool isPrunedValue(unsigned ValNo, JoinVals &Other);
1310
1311 public:
1312   JoinVals(LiveInterval &li, unsigned subIdx,
1313            SmallVectorImpl<VNInfo*> &newVNInfo,
1314            const CoalescerPair &cp,
1315            LiveIntervals *lis,
1316            const TargetRegisterInfo *tri)
1317     : LI(li), SubIdx(subIdx), NewVNInfo(newVNInfo), CP(cp), LIS(lis),
1318       Indexes(LIS->getSlotIndexes()), TRI(tri),
1319       Assignments(LI.getNumValNums(), -1), Vals(LI.getNumValNums())
1320   {}
1321
1322   /// Analyze defs in LI and compute a value mapping in NewVNInfo.
1323   /// Returns false if any conflicts were impossible to resolve.
1324   bool mapValues(JoinVals &Other);
1325
1326   /// Try to resolve conflicts that require all values to be mapped.
1327   /// Returns false if any conflicts were impossible to resolve.
1328   bool resolveConflicts(JoinVals &Other);
1329
1330   /// Prune the live range of values in Other.LI where they would conflict with
1331   /// CR_Replace values in LI. Collect end points for restoring the live range
1332   /// after joining.
1333   void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints);
1334
1335   /// Erase any machine instructions that have been coalesced away.
1336   /// Add erased instructions to ErasedInstrs.
1337   /// Add foreign virtual registers to ShrinkRegs if their live range ended at
1338   /// the erased instrs.
1339   void eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs,
1340                    SmallVectorImpl<unsigned> &ShrinkRegs);
1341
1342   /// Get the value assignments suitable for passing to LiveInterval::join.
1343   const int *getAssignments() const { return Assignments.data(); }
1344 };
1345 } // end anonymous namespace
1346
1347 /// Compute the bitmask of lanes actually written by DefMI.
1348 /// Set Redef if there are any partial register definitions that depend on the
1349 /// previous value of the register.
1350 unsigned JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef) {
1351   unsigned L = 0;
1352   for (ConstMIOperands MO(DefMI); MO.isValid(); ++MO) {
1353     if (!MO->isReg() || MO->getReg() != LI.reg || !MO->isDef())
1354       continue;
1355     L |= TRI->getSubRegIndexLaneMask(
1356            TRI->composeSubRegIndices(SubIdx, MO->getSubReg()));
1357     if (MO->readsReg())
1358       Redef = true;
1359   }
1360   return L;
1361 }
1362
1363 /// Find the ultimate value that VNI was copied from.
1364 VNInfo *JoinVals::stripCopies(VNInfo *VNI) {
1365   while (!VNI->isPHIDef()) {
1366     MachineInstr *MI = Indexes->getInstructionFromIndex(VNI->def);
1367     assert(MI && "No defining instruction");
1368     if (!MI->isFullCopy())
1369       break;
1370     unsigned Reg = MI->getOperand(1).getReg();
1371     if (!TargetRegisterInfo::isVirtualRegister(Reg))
1372       break;
1373     LiveRangeQuery LRQ(LIS->getInterval(Reg), VNI->def);
1374     if (!LRQ.valueIn())
1375       break;
1376     VNI = LRQ.valueIn();
1377   }
1378   return VNI;
1379 }
1380
1381 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
1382 /// Return a conflict resolution when possible, but leave the hard cases as
1383 /// CR_Unresolved.
1384 /// Recursively calls computeAssignment() on this and Other, guaranteeing that
1385 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
1386 /// The recursion always goes upwards in the dominator tree, making loops
1387 /// impossible.
1388 JoinVals::ConflictResolution
1389 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
1390   Val &V = Vals[ValNo];
1391   assert(!V.isAnalyzed() && "Value has already been analyzed!");
1392   VNInfo *VNI = LI.getValNumInfo(ValNo);
1393   if (VNI->isUnused()) {
1394     V.WriteLanes = ~0u;
1395     return CR_Keep;
1396   }
1397
1398   // Get the instruction defining this value, compute the lanes written.
1399   const MachineInstr *DefMI = 0;
1400   if (VNI->isPHIDef()) {
1401     // Conservatively assume that all lanes in a PHI are valid.
1402     V.ValidLanes = V.WriteLanes = TRI->getSubRegIndexLaneMask(SubIdx);
1403   } else {
1404     DefMI = Indexes->getInstructionFromIndex(VNI->def);
1405     bool Redef = false;
1406     V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
1407
1408     // If this is a read-modify-write instruction, there may be more valid
1409     // lanes than the ones written by this instruction.
1410     // This only covers partial redef operands. DefMI may have normal use
1411     // operands reading the register. They don't contribute valid lanes.
1412     //
1413     // This adds ssub1 to the set of valid lanes in %src:
1414     //
1415     //   %src:ssub1<def> = FOO
1416     //
1417     // This leaves only ssub1 valid, making any other lanes undef:
1418     //
1419     //   %src:ssub1<def,read-undef> = FOO %src:ssub2
1420     //
1421     // The <read-undef> flag on the def operand means that old lane values are
1422     // not important.
1423     if (Redef) {
1424       V.RedefVNI = LiveRangeQuery(LI, VNI->def).valueIn();
1425       assert(V.RedefVNI && "Instruction is reading nonexistent value");
1426       computeAssignment(V.RedefVNI->id, Other);
1427       V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
1428     }
1429
1430     // An IMPLICIT_DEF writes undef values.
1431     if (DefMI->isImplicitDef()) {
1432       V.IsImplicitDef = true;
1433       V.ValidLanes &= ~V.WriteLanes;
1434     }
1435   }
1436
1437   // Find the value in Other that overlaps VNI->def, if any.
1438   LiveRangeQuery OtherLRQ(Other.LI, VNI->def);
1439
1440   // It is possible that both values are defined by the same instruction, or
1441   // the values are PHIs defined in the same block. When that happens, the two
1442   // values should be merged into one, but not into any preceding value.
1443   // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
1444   if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
1445     assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
1446
1447     // One value stays, the other is merged. Keep the earlier one, or the first
1448     // one we see.
1449     if (OtherVNI->def < VNI->def)
1450       Other.computeAssignment(OtherVNI->id, *this);
1451     else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
1452       // This is an early-clobber def overlapping a live-in value in the other
1453       // register. Not mergeable.
1454       V.OtherVNI = OtherLRQ.valueIn();
1455       return CR_Impossible;
1456     }
1457     V.OtherVNI = OtherVNI;
1458     Val &OtherV = Other.Vals[OtherVNI->id];
1459     // Keep this value, check for conflicts when analyzing OtherVNI.
1460     if (!OtherV.isAnalyzed())
1461       return CR_Keep;
1462     // Both sides have been analyzed now.
1463     // Allow overlapping PHI values. Any real interference would show up in a
1464     // predecessor, the PHI itself can't introduce any conflicts.
1465     if (VNI->isPHIDef())
1466       return CR_Merge;
1467     if (V.ValidLanes & OtherV.ValidLanes)
1468       // Overlapping lanes can't be resolved.
1469       return CR_Impossible;
1470     else
1471       return CR_Merge;
1472   }
1473
1474   // No simultaneous def. Is Other live at the def?
1475   V.OtherVNI = OtherLRQ.valueIn();
1476   if (!V.OtherVNI)
1477     // No overlap, no conflict.
1478     return CR_Keep;
1479
1480   assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
1481
1482   // We have overlapping values, or possibly a kill of Other.
1483   // Recursively compute assignments up the dominator tree.
1484   Other.computeAssignment(V.OtherVNI->id, *this);
1485   const Val &OtherV = Other.Vals[V.OtherVNI->id];
1486
1487   // Allow overlapping PHI values. Any real interference would show up in a
1488   // predecessor, the PHI itself can't introduce any conflicts.
1489   if (VNI->isPHIDef())
1490     return CR_Replace;
1491
1492   // Check for simple erasable conflicts.
1493   if (DefMI->isImplicitDef())
1494     return CR_Erase;
1495
1496   // Include the non-conflict where DefMI is a coalescable copy that kills
1497   // OtherVNI. We still want the copy erased and value numbers merged.
1498   if (CP.isCoalescable(DefMI)) {
1499     // Some of the lanes copied from OtherVNI may be undef, making them undef
1500     // here too.
1501     V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
1502     return CR_Erase;
1503   }
1504
1505   // This may not be a real conflict if DefMI simply kills Other and defines
1506   // VNI.
1507   if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
1508     return CR_Keep;
1509
1510   // Handle the case where VNI and OtherVNI can be proven to be identical:
1511   //
1512   //   %other = COPY %ext
1513   //   %this  = COPY %ext <-- Erase this copy
1514   //
1515   if (DefMI->isFullCopy() && !CP.isPartial() &&
1516       stripCopies(VNI) == stripCopies(V.OtherVNI))
1517     return CR_Erase;
1518
1519   // If the lanes written by this instruction were all undef in OtherVNI, it is
1520   // still safe to join the live ranges. This can't be done with a simple value
1521   // mapping, though - OtherVNI will map to multiple values:
1522   //
1523   //   1 %dst:ssub0 = FOO                <-- OtherVNI
1524   //   2 %src = BAR                      <-- VNI
1525   //   3 %dst:ssub1 = COPY %src<kill>    <-- Eliminate this copy.
1526   //   4 BAZ %dst<kill>
1527   //   5 QUUX %src<kill>
1528   //
1529   // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
1530   // handles this complex value mapping.
1531   if ((V.WriteLanes & OtherV.ValidLanes) == 0)
1532     return CR_Replace;
1533
1534   // If the other live range is killed by DefMI and the live ranges are still
1535   // overlapping, it must be because we're looking at an early clobber def:
1536   //
1537   //   %dst<def,early-clobber> = ASM %src<kill>
1538   //
1539   // In this case, it is illegal to merge the two live ranges since the early
1540   // clobber def would clobber %src before it was read.
1541   if (OtherLRQ.isKill()) {
1542     // This case where the def doesn't overlap the kill is handled above.
1543     assert(VNI->def.isEarlyClobber() &&
1544            "Only early clobber defs can overlap a kill");
1545     return CR_Impossible;
1546   }
1547
1548   // VNI is clobbering live lanes in OtherVNI, but there is still the
1549   // possibility that no instructions actually read the clobbered lanes.
1550   // If we're clobbering all the lanes in OtherVNI, at least one must be read.
1551   // Otherwise Other.LI wouldn't be live here.
1552   if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes) == 0)
1553     return CR_Impossible;
1554
1555   // We need to verify that no instructions are reading the clobbered lanes. To
1556   // save compile time, we'll only check that locally. Don't allow the tainted
1557   // value to escape the basic block.
1558   MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1559   if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
1560     return CR_Impossible;
1561
1562   // There are still some things that could go wrong besides clobbered lanes
1563   // being read, for example OtherVNI may be only partially redefined in MBB,
1564   // and some clobbered lanes could escape the block. Save this analysis for
1565   // resolveConflicts() when all values have been mapped. We need to know
1566   // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
1567   // that now - the recursive analyzeValue() calls must go upwards in the
1568   // dominator tree.
1569   return CR_Unresolved;
1570 }
1571
1572 /// Compute the value assignment for ValNo in LI.
1573 /// This may be called recursively by analyzeValue(), but never for a ValNo on
1574 /// the stack.
1575 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
1576   Val &V = Vals[ValNo];
1577   if (V.isAnalyzed()) {
1578     // Recursion should always move up the dominator tree, so ValNo is not
1579     // supposed to reappear before it has been assigned.
1580     assert(Assignments[ValNo] != -1 && "Bad recursion?");
1581     return;
1582   }
1583   switch ((V.Resolution = analyzeValue(ValNo, Other))) {
1584   case CR_Erase:
1585   case CR_Merge:
1586     // Merge this ValNo into OtherVNI.
1587     assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
1588     assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
1589     Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
1590     DEBUG(dbgs() << "\t\tmerge " << PrintReg(LI.reg) << ':' << ValNo << '@'
1591                  << LI.getValNumInfo(ValNo)->def << " into "
1592                  << PrintReg(Other.LI.reg) << ':' << V.OtherVNI->id << '@'
1593                  << V.OtherVNI->def << " --> @"
1594                  << NewVNInfo[Assignments[ValNo]]->def << '\n');
1595     break;
1596   case CR_Replace:
1597   case CR_Unresolved:
1598     // The other value is going to be pruned if this join is successful.
1599     assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
1600     Other.Vals[V.OtherVNI->id].Pruned = true;
1601     // Fall through.
1602   default:
1603     // This value number needs to go in the final joined live range.
1604     Assignments[ValNo] = NewVNInfo.size();
1605     NewVNInfo.push_back(LI.getValNumInfo(ValNo));
1606     break;
1607   }
1608 }
1609
1610 bool JoinVals::mapValues(JoinVals &Other) {
1611   for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1612     computeAssignment(i, Other);
1613     if (Vals[i].Resolution == CR_Impossible) {
1614       DEBUG(dbgs() << "\t\tinterference at " << PrintReg(LI.reg) << ':' << i
1615                    << '@' << LI.getValNumInfo(i)->def << '\n');
1616       return false;
1617     }
1618   }
1619   return true;
1620 }
1621
1622 /// Assuming ValNo is going to clobber some valid lanes in Other.LI, compute
1623 /// the extent of the tainted lanes in the block.
1624 ///
1625 /// Multiple values in Other.LI can be affected since partial redefinitions can
1626 /// preserve previously tainted lanes.
1627 ///
1628 ///   1 %dst = VLOAD           <-- Define all lanes in %dst
1629 ///   2 %src = FOO             <-- ValNo to be joined with %dst:ssub0
1630 ///   3 %dst:ssub1 = BAR       <-- Partial redef doesn't clear taint in ssub0
1631 ///   4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
1632 ///
1633 /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
1634 /// entry to TaintedVals.
1635 ///
1636 /// Returns false if the tainted lanes extend beyond the basic block.
1637 bool JoinVals::
1638 taintExtent(unsigned ValNo, unsigned TaintedLanes, JoinVals &Other,
1639             SmallVectorImpl<std::pair<SlotIndex, unsigned> > &TaintExtent) {
1640   VNInfo *VNI = LI.getValNumInfo(ValNo);
1641   MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1642   SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
1643
1644   // Scan Other.LI from VNI.def to MBBEnd.
1645   LiveInterval::iterator OtherI = Other.LI.find(VNI->def);
1646   assert(OtherI != Other.LI.end() && "No conflict?");
1647   do {
1648     // OtherI is pointing to a tainted value. Abort the join if the tainted
1649     // lanes escape the block.
1650     SlotIndex End = OtherI->end;
1651     if (End >= MBBEnd) {
1652       DEBUG(dbgs() << "\t\ttaints global " << PrintReg(Other.LI.reg) << ':'
1653                    << OtherI->valno->id << '@' << OtherI->start << '\n');
1654       return false;
1655     }
1656     DEBUG(dbgs() << "\t\ttaints local " << PrintReg(Other.LI.reg) << ':'
1657                  << OtherI->valno->id << '@' << OtherI->start
1658                  << " to " << End << '\n');
1659     // A dead def is not a problem.
1660     if (End.isDead())
1661       break;
1662     TaintExtent.push_back(std::make_pair(End, TaintedLanes));
1663
1664     // Check for another def in the MBB.
1665     if (++OtherI == Other.LI.end() || OtherI->start >= MBBEnd)
1666       break;
1667
1668     // Lanes written by the new def are no longer tainted.
1669     const Val &OV = Other.Vals[OtherI->valno->id];
1670     TaintedLanes &= ~OV.WriteLanes;
1671     if (!OV.RedefVNI)
1672       break;
1673   } while (TaintedLanes);
1674   return true;
1675 }
1676
1677 /// Return true if MI uses any of the given Lanes from Reg.
1678 /// This does not include partial redefinitions of Reg.
1679 bool JoinVals::usesLanes(MachineInstr *MI, unsigned Reg, unsigned SubIdx,
1680                          unsigned Lanes) {
1681   if (MI->isDebugValue())
1682     return false;
1683   for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
1684     if (!MO->isReg() || MO->isDef() || MO->getReg() != Reg)
1685       continue;
1686     if (!MO->readsReg())
1687       continue;
1688     if (Lanes & TRI->getSubRegIndexLaneMask(
1689                   TRI->composeSubRegIndices(SubIdx, MO->getSubReg())))
1690       return true;
1691   }
1692   return false;
1693 }
1694
1695 bool JoinVals::resolveConflicts(JoinVals &Other) {
1696   for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1697     Val &V = Vals[i];
1698     assert (V.Resolution != CR_Impossible && "Unresolvable conflict");
1699     if (V.Resolution != CR_Unresolved)
1700       continue;
1701     DEBUG(dbgs() << "\t\tconflict at " << PrintReg(LI.reg) << ':' << i
1702                  << '@' << LI.getValNumInfo(i)->def << '\n');
1703     ++NumLaneConflicts;
1704     assert(V.OtherVNI && "Inconsistent conflict resolution.");
1705     VNInfo *VNI = LI.getValNumInfo(i);
1706     const Val &OtherV = Other.Vals[V.OtherVNI->id];
1707
1708     // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
1709     // join, those lanes will be tainted with a wrong value. Get the extent of
1710     // the tainted lanes.
1711     unsigned TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
1712     SmallVector<std::pair<SlotIndex, unsigned>, 8> TaintExtent;
1713     if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
1714       // Tainted lanes would extend beyond the basic block.
1715       return false;
1716
1717     assert(!TaintExtent.empty() && "There should be at least one conflict.");
1718
1719     // Now look at the instructions from VNI->def to TaintExtent (inclusive).
1720     MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1721     MachineBasicBlock::iterator MI = MBB->begin();
1722     if (!VNI->isPHIDef()) {
1723       MI = Indexes->getInstructionFromIndex(VNI->def);
1724       // No need to check the instruction defining VNI for reads.
1725       ++MI;
1726     }
1727     assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
1728            "Interference ends on VNI->def. Should have been handled earlier");
1729     MachineInstr *LastMI =
1730       Indexes->getInstructionFromIndex(TaintExtent.front().first);
1731     assert(LastMI && "Range must end at a proper instruction");
1732     unsigned TaintNum = 0;
1733     for(;;) {
1734       assert(MI != MBB->end() && "Bad LastMI");
1735       if (usesLanes(MI, Other.LI.reg, Other.SubIdx, TaintedLanes)) {
1736         DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
1737         return false;
1738       }
1739       // LastMI is the last instruction to use the current value.
1740       if (&*MI == LastMI) {
1741         if (++TaintNum == TaintExtent.size())
1742           break;
1743         LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
1744         assert(LastMI && "Range must end at a proper instruction");
1745         TaintedLanes = TaintExtent[TaintNum].second;
1746       }
1747       ++MI;
1748     }
1749
1750     // The tainted lanes are unused.
1751     V.Resolution = CR_Replace;
1752     ++NumLaneResolves;
1753   }
1754   return true;
1755 }
1756
1757 // Determine if ValNo is a copy of a value number in LI or Other.LI that will
1758 // be pruned:
1759 //
1760 //   %dst = COPY %src
1761 //   %src = COPY %dst  <-- This value to be pruned.
1762 //   %dst = COPY %src  <-- This value is a copy of a pruned value.
1763 //
1764 bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
1765   Val &V = Vals[ValNo];
1766   if (V.Pruned || V.PrunedComputed)
1767     return V.Pruned;
1768
1769   if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
1770     return V.Pruned;
1771
1772   // Follow copies up the dominator tree and check if any intermediate value
1773   // has been pruned.
1774   V.PrunedComputed = true;
1775   V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
1776   return V.Pruned;
1777 }
1778
1779 void JoinVals::pruneValues(JoinVals &Other,
1780                            SmallVectorImpl<SlotIndex> &EndPoints) {
1781   for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1782     SlotIndex Def = LI.getValNumInfo(i)->def;
1783     switch (Vals[i].Resolution) {
1784     case CR_Keep:
1785       break;
1786     case CR_Replace: {
1787       // This value takes precedence over the value in Other.LI.
1788       LIS->pruneValue(&Other.LI, Def, &EndPoints);
1789       // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
1790       // instructions are only inserted to provide a live-out value for PHI
1791       // predecessors, so the instruction should simply go away once its value
1792       // has been replaced.
1793       Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
1794       bool EraseImpDef = OtherV.IsImplicitDef && OtherV.Resolution == CR_Keep;
1795       if (!Def.isBlock()) {
1796         // Remove <def,read-undef> flags. This def is now a partial redef.
1797         // Also remove <def,dead> flags since the joined live range will
1798         // continue past this instruction.
1799         for (MIOperands MO(Indexes->getInstructionFromIndex(Def));
1800              MO.isValid(); ++MO)
1801           if (MO->isReg() && MO->isDef() && MO->getReg() == LI.reg) {
1802             MO->setIsUndef(EraseImpDef);
1803             MO->setIsDead(false);
1804           }
1805         // This value will reach instructions below, but we need to make sure
1806         // the live range also reaches the instruction at Def.
1807         if (!EraseImpDef)
1808           EndPoints.push_back(Def);
1809       }
1810       DEBUG(dbgs() << "\t\tpruned " << PrintReg(Other.LI.reg) << " at " << Def
1811                    << ": " << Other.LI << '\n');
1812       break;
1813     }
1814     case CR_Erase:
1815     case CR_Merge:
1816       if (isPrunedValue(i, Other)) {
1817         // This value is ultimately a copy of a pruned value in LI or Other.LI.
1818         // We can no longer trust the value mapping computed by
1819         // computeAssignment(), the value that was originally copied could have
1820         // been replaced.
1821         LIS->pruneValue(&LI, Def, &EndPoints);
1822         DEBUG(dbgs() << "\t\tpruned all of " << PrintReg(LI.reg) << " at "
1823                      << Def << ": " << LI << '\n');
1824       }
1825       break;
1826     case CR_Unresolved:
1827     case CR_Impossible:
1828       llvm_unreachable("Unresolved conflicts");
1829     }
1830   }
1831 }
1832
1833 void JoinVals::eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs,
1834                            SmallVectorImpl<unsigned> &ShrinkRegs) {
1835   for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1836     // Get the def location before markUnused() below invalidates it.
1837     SlotIndex Def = LI.getValNumInfo(i)->def;
1838     switch (Vals[i].Resolution) {
1839     case CR_Keep:
1840       // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
1841       // longer. The IMPLICIT_DEF instructions are only inserted by
1842       // PHIElimination to guarantee that all PHI predecessors have a value.
1843       if (!Vals[i].IsImplicitDef || !Vals[i].Pruned)
1844         break;
1845       // Remove value number i from LI. Note that this VNInfo is still present
1846       // in NewVNInfo, so it will appear as an unused value number in the final
1847       // joined interval.
1848       LI.getValNumInfo(i)->markUnused();
1849       LI.removeValNo(LI.getValNumInfo(i));
1850       DEBUG(dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LI << '\n');
1851       // FALL THROUGH.
1852
1853     case CR_Erase: {
1854       MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
1855       assert(MI && "No instruction to erase");
1856       if (MI->isCopy()) {
1857         unsigned Reg = MI->getOperand(1).getReg();
1858         if (TargetRegisterInfo::isVirtualRegister(Reg) &&
1859             Reg != CP.getSrcReg() && Reg != CP.getDstReg())
1860           ShrinkRegs.push_back(Reg);
1861       }
1862       ErasedInstrs.insert(MI);
1863       DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
1864       LIS->RemoveMachineInstrFromMaps(MI);
1865       MI->eraseFromParent();
1866       break;
1867     }
1868     default:
1869       break;
1870     }
1871   }
1872 }
1873
1874 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
1875   SmallVector<VNInfo*, 16> NewVNInfo;
1876   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1877   LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
1878   JoinVals RHSVals(RHS, CP.getSrcIdx(), NewVNInfo, CP, LIS, TRI);
1879   JoinVals LHSVals(LHS, CP.getDstIdx(), NewVNInfo, CP, LIS, TRI);
1880
1881   DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1882                << "\n\t\tLHS = " << PrintReg(CP.getDstReg()) << ' ' << LHS
1883                << '\n');
1884
1885   // First compute NewVNInfo and the simple value mappings.
1886   // Detect impossible conflicts early.
1887   if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
1888     return false;
1889
1890   // Some conflicts can only be resolved after all values have been mapped.
1891   if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
1892     return false;
1893
1894   // All clear, the live ranges can be merged.
1895
1896   // The merging algorithm in LiveInterval::join() can't handle conflicting
1897   // value mappings, so we need to remove any live ranges that overlap a
1898   // CR_Replace resolution. Collect a set of end points that can be used to
1899   // restore the live range after joining.
1900   SmallVector<SlotIndex, 8> EndPoints;
1901   LHSVals.pruneValues(RHSVals, EndPoints);
1902   RHSVals.pruneValues(LHSVals, EndPoints);
1903
1904   // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
1905   // registers to require trimming.
1906   SmallVector<unsigned, 8> ShrinkRegs;
1907   LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
1908   RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
1909   while (!ShrinkRegs.empty())
1910     LIS->shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
1911
1912   // Join RHS into LHS.
1913   LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo,
1914            MRI);
1915
1916   // Kill flags are going to be wrong if the live ranges were overlapping.
1917   // Eventually, we should simply clear all kill flags when computing live
1918   // ranges. They are reinserted after register allocation.
1919   MRI->clearKillFlags(LHS.reg);
1920   MRI->clearKillFlags(RHS.reg);
1921
1922   if (EndPoints.empty())
1923     return true;
1924
1925   // Recompute the parts of the live range we had to remove because of
1926   // CR_Replace conflicts.
1927   DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
1928                << " points: " << LHS << '\n');
1929   LIS->extendToIndices(&LHS, EndPoints);
1930   return true;
1931 }
1932
1933 /// joinIntervals - Attempt to join these two intervals.  On failure, this
1934 /// returns false.
1935 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
1936   return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
1937 }
1938
1939 namespace {
1940   // Information concerning MBB coalescing priority.
1941   struct MBBPriorityInfo {
1942     MachineBasicBlock *MBB;
1943     unsigned Depth;
1944     bool IsSplit;
1945
1946     MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
1947       : MBB(mbb), Depth(depth), IsSplit(issplit) {}
1948   };
1949
1950   // MBBPriorityCompare - Comparison predicate that sorts first based on the
1951   // loop depth of the basic block (the unsigned), and then on the MBB number.
1952   //
1953   // EnableGlobalCopies assumes that the primary sort key is loop depth.
1954   struct MBBPriorityCompare {
1955     bool JoinSplitEdges;
1956
1957     MBBPriorityCompare(bool joinsplits): JoinSplitEdges(joinsplits) {}
1958
1959     bool operator()(const MBBPriorityInfo &LHS,
1960                     const MBBPriorityInfo &RHS) const {
1961       // Deeper loops first
1962       if (LHS.Depth != RHS.Depth)
1963         return LHS.Depth > RHS.Depth;
1964
1965       // Try to unsplit critical edges next.
1966       if (JoinSplitEdges && LHS.IsSplit != RHS.IsSplit)
1967         return LHS.IsSplit;
1968
1969       // Prefer blocks that are more connected in the CFG. This takes care of
1970       // the most difficult copies first while intervals are short.
1971       unsigned cl = LHS.MBB->pred_size() + LHS.MBB->succ_size();
1972       unsigned cr = RHS.MBB->pred_size() + RHS.MBB->succ_size();
1973       if (cl != cr)
1974         return cl > cr;
1975
1976       // As a last resort, sort by block number.
1977       return LHS.MBB->getNumber() < RHS.MBB->getNumber();
1978     }
1979   };
1980 }
1981
1982 /// \returns true if the given copy uses or defines a local live range.
1983 static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) {
1984   if (!Copy->isCopy())
1985     return false;
1986
1987   unsigned SrcReg = Copy->getOperand(1).getReg();
1988   unsigned DstReg = Copy->getOperand(0).getReg();
1989   if (TargetRegisterInfo::isPhysicalRegister(SrcReg)
1990       || TargetRegisterInfo::isPhysicalRegister(DstReg))
1991     return false;
1992
1993   return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg))
1994     || LIS->intervalIsInOneMBB(LIS->getInterval(DstReg));
1995 }
1996
1997 // Try joining WorkList copies starting from index From.
1998 // Null out any successful joins.
1999 bool RegisterCoalescer::
2000 copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) {
2001   bool Progress = false;
2002   for (unsigned i = 0, e = CurrList.size(); i != e; ++i) {
2003     if (!CurrList[i])
2004       continue;
2005     // Skip instruction pointers that have already been erased, for example by
2006     // dead code elimination.
2007     if (ErasedInstrs.erase(CurrList[i])) {
2008       CurrList[i] = 0;
2009       continue;
2010     }
2011     bool Again = false;
2012     bool Success = joinCopy(CurrList[i], Again);
2013     Progress |= Success;
2014     if (Success || !Again)
2015       CurrList[i] = 0;
2016   }
2017   return Progress;
2018 }
2019
2020 void
2021 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
2022   DEBUG(dbgs() << MBB->getName() << ":\n");
2023
2024   // Collect all copy-like instructions in MBB. Don't start coalescing anything
2025   // yet, it might invalidate the iterator.
2026   const unsigned PrevSize = WorkList.size();
2027   if (JoinGlobalCopies) {
2028     // Coalesce copies bottom-up to coalesce local defs before local uses. They
2029     // are not inherently easier to resolve, but slightly preferable until we
2030     // have local live range splitting. In particular this is required by
2031     // cmp+jmp macro fusion.
2032     for (MachineBasicBlock::reverse_iterator
2033            MII = MBB->rbegin(), E = MBB->rend(); MII != E; ++MII) {
2034       if (!MII->isCopyLike())
2035         continue;
2036       if (isLocalCopy(&(*MII), LIS))
2037         LocalWorkList.push_back(&(*MII));
2038       else
2039         WorkList.push_back(&(*MII));
2040     }
2041   }
2042   else {
2043      for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2044           MII != E; ++MII)
2045        if (MII->isCopyLike())
2046          WorkList.push_back(MII);
2047   }
2048   // Try coalescing the collected copies immediately, and remove the nulls.
2049   // This prevents the WorkList from getting too large since most copies are
2050   // joinable on the first attempt.
2051   MutableArrayRef<MachineInstr*>
2052     CurrList(WorkList.begin() + PrevSize, WorkList.end());
2053   if (copyCoalesceWorkList(CurrList))
2054     WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
2055                                (MachineInstr*)0), WorkList.end());
2056 }
2057
2058 void RegisterCoalescer::coalesceLocals() {
2059   copyCoalesceWorkList(LocalWorkList);
2060   for (unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) {
2061     if (LocalWorkList[j])
2062       WorkList.push_back(LocalWorkList[j]);
2063   }
2064   LocalWorkList.clear();
2065 }
2066
2067 void RegisterCoalescer::joinAllIntervals() {
2068   DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
2069   assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around.");
2070
2071   std::vector<MBBPriorityInfo> MBBs;
2072   for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
2073     MachineBasicBlock *MBB = I;
2074     MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB),
2075                                    isSplitEdge(MBB)));
2076   }
2077   std::sort(MBBs.begin(), MBBs.end(), MBBPriorityCompare(JoinSplitEdges));
2078
2079   // Coalesce intervals in MBB priority order.
2080   unsigned CurrDepth = UINT_MAX;
2081   for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
2082     // Try coalescing the collected local copies for deeper loops.
2083     if (JoinGlobalCopies && MBBs[i].Depth < CurrDepth)
2084       coalesceLocals();
2085     copyCoalesceInMBB(MBBs[i].MBB);
2086   }
2087   coalesceLocals();
2088
2089   // Joining intervals can allow other intervals to be joined.  Iteratively join
2090   // until we make no progress.
2091   while (copyCoalesceWorkList(WorkList))
2092     /* empty */ ;
2093 }
2094
2095 void RegisterCoalescer::releaseMemory() {
2096   ErasedInstrs.clear();
2097   WorkList.clear();
2098   DeadDefs.clear();
2099   InflateRegs.clear();
2100 }
2101
2102 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
2103   MF = &fn;
2104   MRI = &fn.getRegInfo();
2105   TM = &fn.getTarget();
2106   TRI = TM->getRegisterInfo();
2107   TII = TM->getInstrInfo();
2108   LIS = &getAnalysis<LiveIntervals>();
2109   LDV = &getAnalysis<LiveDebugVariables>();
2110   AA = &getAnalysis<AliasAnalysis>();
2111   Loops = &getAnalysis<MachineLoopInfo>();
2112
2113   const TargetSubtargetInfo &ST = TM->getSubtarget<TargetSubtargetInfo>();
2114   if (EnableGlobalCopies == cl::BOU_UNSET)
2115     JoinGlobalCopies = ST.enableMachineScheduler();
2116   else
2117     JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE);
2118
2119   if (EnableJoinSplits == cl::BOU_UNSET)
2120     JoinSplitEdges = ST.enableMachineScheduler();
2121   else
2122     JoinSplitEdges = (EnableJoinSplits == cl::BOU_TRUE);
2123
2124   DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
2125                << "********** Function: " << MF->getName() << '\n');
2126
2127   if (VerifyCoalescing)
2128     MF->verify(this, "Before register coalescing");
2129
2130   RegClassInfo.runOnMachineFunction(fn);
2131
2132   // Join (coalesce) intervals if requested.
2133   if (EnableJoining)
2134     joinAllIntervals();
2135
2136   // After deleting a lot of copies, register classes may be less constrained.
2137   // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
2138   // DPR inflation.
2139   array_pod_sort(InflateRegs.begin(), InflateRegs.end());
2140   InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
2141                     InflateRegs.end());
2142   DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
2143   for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
2144     unsigned Reg = InflateRegs[i];
2145     if (MRI->reg_nodbg_empty(Reg))
2146       continue;
2147     if (MRI->recomputeRegClass(Reg, *TM)) {
2148       DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
2149                    << MRI->getRegClass(Reg)->getName() << '\n');
2150       ++NumInflated;
2151     }
2152   }
2153
2154   DEBUG(dump());
2155   DEBUG(LDV->dump());
2156   if (VerifyCoalescing)
2157     MF->verify(this, "After register coalescing");
2158   return true;
2159 }
2160
2161 /// print - Implement the dump method.
2162 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {
2163    LIS->print(O, m);
2164 }