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