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