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