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