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