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