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