[Register Coalescer] Fix wrong live-range information with rematerialization.
[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 "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
23 #include "llvm/CodeGen/LiveRangeEdit.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/RegisterClassInfo.h"
30 #include "llvm/CodeGen/VirtRegMap.h"
31 #include "llvm/IR/Value.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
41 #include <algorithm>
42 #include <cmath>
43 using namespace llvm;
44
45 STATISTIC(numJoins    , "Number of interval joins performed");
46 STATISTIC(numCrossRCs , "Number of cross class joins performed");
47 STATISTIC(numCommutes , "Number of instruction commuting performed");
48 STATISTIC(numExtends  , "Number of copies extended");
49 STATISTIC(NumReMats   , "Number of instructions re-materialized");
50 STATISTIC(NumInflated , "Number of register classes inflated");
51 STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested");
52 STATISTIC(NumLaneResolves,  "Number of dead lane conflicts resolved");
53
54 static cl::opt<bool>
55 EnableJoining("join-liveintervals",
56               cl::desc("Coalesce copies (default=true)"),
57               cl::init(true));
58
59 // Temporary flag to test critical edge unsplitting.
60 static cl::opt<bool>
61 EnableJoinSplits("join-splitedges",
62   cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden);
63
64 // Temporary flag to test global copy optimization.
65 static cl::opt<cl::boolOrDefault>
66 EnableGlobalCopies("join-globalcopies",
67   cl::desc("Coalesce copies that span blocks (default=subtarget)"),
68   cl::init(cl::BOU_UNSET), cl::Hidden);
69
70 static cl::opt<bool>
71 VerifyCoalescing("verify-coalescing",
72          cl::desc("Verify machine instrs before and after register coalescing"),
73          cl::Hidden);
74
75 namespace {
76   class RegisterCoalescer : public MachineFunctionPass,
77                             private LiveRangeEdit::Delegate {
78     MachineFunction* MF;
79     MachineRegisterInfo* MRI;
80     const TargetMachine* TM;
81     const TargetRegisterInfo* TRI;
82     const TargetInstrInfo* TII;
83     LiveIntervals *LIS;
84     const MachineLoopInfo* Loops;
85     AliasAnalysis *AA;
86     RegisterClassInfo RegClassInfo;
87
88     /// \brief True if the coalescer should aggressively coalesce global copies
89     /// in favor of keeping local copies.
90     bool JoinGlobalCopies;
91
92     /// \brief True if the coalescer should aggressively coalesce fall-thru
93     /// blocks exclusively containing copies.
94     bool JoinSplitEdges;
95
96     /// WorkList - Copy instructions yet to be coalesced.
97     SmallVector<MachineInstr*, 8> WorkList;
98     SmallVector<MachineInstr*, 8> LocalWorkList;
99
100     /// ErasedInstrs - Set of instruction pointers that have been erased, and
101     /// that may be present in WorkList.
102     SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
103
104     /// Dead instructions that are about to be deleted.
105     SmallVector<MachineInstr*, 8> DeadDefs;
106
107     /// Virtual registers to be considered for register class inflation.
108     SmallVector<unsigned, 8> InflateRegs;
109
110     /// Recursively eliminate dead defs in DeadDefs.
111     void eliminateDeadDefs();
112
113     /// LiveRangeEdit callback.
114     void LRE_WillEraseInstruction(MachineInstr *MI) override;
115
116     /// coalesceLocals - coalesce the LocalWorkList.
117     void coalesceLocals();
118
119     /// joinAllIntervals - join compatible live intervals
120     void joinAllIntervals();
121
122     /// copyCoalesceInMBB - Coalesce copies in the specified MBB, putting
123     /// copies that cannot yet be coalesced into WorkList.
124     void copyCoalesceInMBB(MachineBasicBlock *MBB);
125
126     /// copyCoalesceWorkList - Try to coalesce all copies in CurrList. Return
127     /// true if any progress was made.
128     bool copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList);
129
130     /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
131     /// which are the src/dst of the copy instruction CopyMI.  This returns
132     /// true if the copy was successfully coalesced away. If it is not
133     /// currently possible to coalesce this interval, but it may be possible if
134     /// other things get coalesced, then it returns true by reference in
135     /// 'Again'.
136     bool joinCopy(MachineInstr *TheCopy, bool &Again);
137
138     /// joinIntervals - Attempt to join these two intervals.  On failure, this
139     /// returns false.  The output "SrcInt" will not have been modified, so we
140     /// can use this information below to update aliases.
141     bool joinIntervals(CoalescerPair &CP);
142
143     /// Attempt joining two virtual registers. Return true on success.
144     bool joinVirtRegs(CoalescerPair &CP);
145
146     /// Attempt joining with a reserved physreg.
147     bool joinReservedPhysReg(CoalescerPair &CP);
148
149     /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
150     /// the source value number is defined by a copy from the destination reg
151     /// see if we can merge these two destination reg valno# into a single
152     /// value number, eliminating a copy.
153     bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
154
155     /// hasOtherReachingDefs - Return true if there are definitions of IntB
156     /// other than BValNo val# that can reach uses of AValno val# of IntA.
157     bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
158                               VNInfo *AValNo, VNInfo *BValNo);
159
160     /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy.
161     /// If the source value number is defined by a commutable instruction and
162     /// its other operand is coalesced to the copy dest register, see if we
163     /// can transform the copy into a noop by commuting the definition.
164     bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
165
166     /// reMaterializeTrivialDef - If the source of a copy is defined by a
167     /// trivial computation, replace the copy by rematerialize the definition.
168     bool reMaterializeTrivialDef(CoalescerPair &CP, MachineInstr *CopyMI,
169                                  bool &IsDefCopy);
170
171     /// canJoinPhys - Return true if a physreg copy should be joined.
172     bool canJoinPhys(const CoalescerPair &CP);
173
174     /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
175     /// update the subregister number if it is not zero. If DstReg is a
176     /// physical register and the existing subregister number of the def / use
177     /// being updated is not zero, make sure to set it to the correct physical
178     /// subregister.
179     void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
180
181     /// eliminateUndefCopy - Handle copies of undef values.
182     bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
183
184   public:
185     static char ID; // Class identification, replacement for typeinfo
186     RegisterCoalescer() : MachineFunctionPass(ID) {
187       initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
188     }
189
190     void getAnalysisUsage(AnalysisUsage &AU) const override;
191
192     void releaseMemory() override;
193
194     /// runOnMachineFunction - pass entry point
195     bool runOnMachineFunction(MachineFunction&) override;
196
197     /// print - Implement the dump method.
198     void print(raw_ostream &O, const Module* = 0) const override;
199   };
200 } /// end anonymous namespace
201
202 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
203
204 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
205                       "Simple Register Coalescing", false, false)
206 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
207 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
208 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
209 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
210 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
211                     "Simple Register Coalescing", false, false)
212
213 char RegisterCoalescer::ID = 0;
214
215 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
216                         unsigned &Src, unsigned &Dst,
217                         unsigned &SrcSub, unsigned &DstSub) {
218   if (MI->isCopy()) {
219     Dst = MI->getOperand(0).getReg();
220     DstSub = MI->getOperand(0).getSubReg();
221     Src = MI->getOperand(1).getReg();
222     SrcSub = MI->getOperand(1).getSubReg();
223   } else if (MI->isSubregToReg()) {
224     Dst = MI->getOperand(0).getReg();
225     DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
226                                       MI->getOperand(3).getImm());
227     Src = MI->getOperand(2).getReg();
228     SrcSub = MI->getOperand(2).getSubReg();
229   } else
230     return false;
231   return true;
232 }
233
234 // Return true if this block should be vacated by the coalescer to eliminate
235 // branches. The important cases to handle in the coalescer are critical edges
236 // split during phi elimination which contain only copies. Simple blocks that
237 // contain non-branches should also be vacated, but this can be handled by an
238 // earlier pass similar to early if-conversion.
239 static bool isSplitEdge(const MachineBasicBlock *MBB) {
240   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
241     return false;
242
243   for (MachineBasicBlock::const_iterator MII = MBB->begin(), E = MBB->end();
244        MII != E; ++MII) {
245     if (!MII->isCopyLike() && !MII->isUnconditionalBranch())
246       return false;
247   }
248   return true;
249 }
250
251 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
252   SrcReg = DstReg = 0;
253   SrcIdx = DstIdx = 0;
254   NewRC = 0;
255   Flipped = CrossClass = false;
256
257   unsigned Src, Dst, SrcSub, DstSub;
258   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
259     return false;
260   Partial = SrcSub || DstSub;
261
262   // If one register is a physreg, it must be Dst.
263   if (TargetRegisterInfo::isPhysicalRegister(Src)) {
264     if (TargetRegisterInfo::isPhysicalRegister(Dst))
265       return false;
266     std::swap(Src, Dst);
267     std::swap(SrcSub, DstSub);
268     Flipped = true;
269   }
270
271   const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
272
273   if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
274     // Eliminate DstSub on a physreg.
275     if (DstSub) {
276       Dst = TRI.getSubReg(Dst, DstSub);
277       if (!Dst) return false;
278       DstSub = 0;
279     }
280
281     // Eliminate SrcSub by picking a corresponding Dst superregister.
282     if (SrcSub) {
283       Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
284       if (!Dst) return false;
285     } else if (!MRI.getRegClass(Src)->contains(Dst)) {
286       return false;
287     }
288   } else {
289     // Both registers are virtual.
290     const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
291     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
292
293     // Both registers have subreg indices.
294     if (SrcSub && DstSub) {
295       // Copies between different sub-registers are never coalescable.
296       if (Src == Dst && SrcSub != DstSub)
297         return false;
298
299       NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
300                                          SrcIdx, DstIdx);
301       if (!NewRC)
302         return false;
303     } else if (DstSub) {
304       // SrcReg will be merged with a sub-register of DstReg.
305       SrcIdx = DstSub;
306       NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
307     } else if (SrcSub) {
308       // DstReg will be merged with a sub-register of SrcReg.
309       DstIdx = SrcSub;
310       NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
311     } else {
312       // This is a straight copy without sub-registers.
313       NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
314     }
315
316     // The combined constraint may be impossible to satisfy.
317     if (!NewRC)
318       return false;
319
320     // Prefer SrcReg to be a sub-register of DstReg.
321     // FIXME: Coalescer should support subregs symmetrically.
322     if (DstIdx && !SrcIdx) {
323       std::swap(Src, Dst);
324       std::swap(SrcIdx, DstIdx);
325       Flipped = !Flipped;
326     }
327
328     CrossClass = NewRC != DstRC || NewRC != SrcRC;
329   }
330   // Check our invariants
331   assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
332   assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
333          "Cannot have a physical SubIdx");
334   SrcReg = Src;
335   DstReg = Dst;
336   return true;
337 }
338
339 bool CoalescerPair::flip() {
340   if (TargetRegisterInfo::isPhysicalRegister(DstReg))
341     return false;
342   std::swap(SrcReg, DstReg);
343   std::swap(SrcIdx, DstIdx);
344   Flipped = !Flipped;
345   return true;
346 }
347
348 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
349   if (!MI)
350     return false;
351   unsigned Src, Dst, SrcSub, DstSub;
352   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
353     return false;
354
355   // Find the virtual register that is SrcReg.
356   if (Dst == SrcReg) {
357     std::swap(Src, Dst);
358     std::swap(SrcSub, DstSub);
359   } else if (Src != SrcReg) {
360     return false;
361   }
362
363   // Now check that Dst matches DstReg.
364   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
365     if (!TargetRegisterInfo::isPhysicalRegister(Dst))
366       return false;
367     assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
368     // DstSub could be set for a physreg from INSERT_SUBREG.
369     if (DstSub)
370       Dst = TRI.getSubReg(Dst, DstSub);
371     // Full copy of Src.
372     if (!SrcSub)
373       return DstReg == Dst;
374     // This is a partial register copy. Check that the parts match.
375     return TRI.getSubReg(DstReg, SrcSub) == Dst;
376   } else {
377     // DstReg is virtual.
378     if (DstReg != Dst)
379       return false;
380     // Registers match, do the subregisters line up?
381     return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
382            TRI.composeSubRegIndices(DstIdx, DstSub);
383   }
384 }
385
386 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
387   AU.setPreservesCFG();
388   AU.addRequired<AliasAnalysis>();
389   AU.addRequired<LiveIntervals>();
390   AU.addPreserved<LiveIntervals>();
391   AU.addPreserved<SlotIndexes>();
392   AU.addRequired<MachineLoopInfo>();
393   AU.addPreserved<MachineLoopInfo>();
394   AU.addPreservedID(MachineDominatorsID);
395   MachineFunctionPass::getAnalysisUsage(AU);
396 }
397
398 void RegisterCoalescer::eliminateDeadDefs() {
399   SmallVector<unsigned, 8> NewRegs;
400   LiveRangeEdit(0, NewRegs, *MF, *LIS, 0, this).eliminateDeadDefs(DeadDefs);
401 }
402
403 // Callback from eliminateDeadDefs().
404 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
405   // MI may be in WorkList. Make sure we don't visit it.
406   ErasedInstrs.insert(MI);
407 }
408
409 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
410 /// being the source and IntB being the dest, thus this defines a value number
411 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
412 /// see if we can merge these two pieces of B into a single value number,
413 /// eliminating a copy.  For example:
414 ///
415 ///  A3 = B0
416 ///    ...
417 ///  B1 = A3      <- this copy
418 ///
419 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
420 /// value number to be replaced with B0 (which simplifies the B liveinterval).
421 ///
422 /// This returns true if an interval was modified.
423 ///
424 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
425                                              MachineInstr *CopyMI) {
426   assert(!CP.isPartial() && "This doesn't work for partial copies.");
427   assert(!CP.isPhys() && "This doesn't work for physreg copies.");
428
429   LiveInterval &IntA =
430     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
431   LiveInterval &IntB =
432     LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
433   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
434
435   // BValNo is a value number in B that is defined by a copy from A.  'B1' in
436   // the example above.
437   LiveInterval::iterator BS = IntB.FindSegmentContaining(CopyIdx);
438   if (BS == IntB.end()) return false;
439   VNInfo *BValNo = BS->valno;
440
441   // Get the location that B is defined at.  Two options: either this value has
442   // an unknown definition point or it is defined at CopyIdx.  If unknown, we
443   // can't process it.
444   if (BValNo->def != CopyIdx) return false;
445
446   // AValNo is the value number in A that defines the copy, A3 in the example.
447   SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
448   LiveInterval::iterator AS = IntA.FindSegmentContaining(CopyUseIdx);
449   // The live segment might not exist after fun with physreg coalescing.
450   if (AS == IntA.end()) return false;
451   VNInfo *AValNo = AS->valno;
452
453   // If AValNo is defined as a copy from IntB, we can potentially process this.
454   // Get the instruction that defines this value number.
455   MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
456   // Don't allow any partial copies, even if isCoalescable() allows them.
457   if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
458     return false;
459
460   // Get the Segment in IntB that this value number starts with.
461   LiveInterval::iterator ValS =
462     IntB.FindSegmentContaining(AValNo->def.getPrevSlot());
463   if (ValS == IntB.end())
464     return false;
465
466   // Make sure that the end of the live segment is inside the same block as
467   // CopyMI.
468   MachineInstr *ValSEndInst =
469     LIS->getInstructionFromIndex(ValS->end.getPrevSlot());
470   if (!ValSEndInst || ValSEndInst->getParent() != CopyMI->getParent())
471     return false;
472
473   // Okay, we now know that ValS ends in the same block that the CopyMI
474   // live-range starts.  If there are no intervening live segments between them
475   // in IntB, we can merge them.
476   if (ValS+1 != BS) return false;
477
478   DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI));
479
480   SlotIndex FillerStart = ValS->end, FillerEnd = BS->start;
481   // We are about to delete CopyMI, so need to remove it as the 'instruction
482   // that defines this value #'. Update the valnum with the new defining
483   // instruction #.
484   BValNo->def = FillerStart;
485
486   // Okay, we can merge them.  We need to insert a new liverange:
487   // [ValS.end, BS.begin) of either value number, then we merge the
488   // two value numbers.
489   IntB.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo));
490
491   // Okay, merge "B1" into the same value number as "B0".
492   if (BValNo != ValS->valno)
493     IntB.MergeValueNumberInto(BValNo, ValS->valno);
494   DEBUG(dbgs() << "   result = " << IntB << '\n');
495
496   // If the source instruction was killing the source register before the
497   // merge, unset the isKill marker given the live range has been extended.
498   int UIdx = ValSEndInst->findRegisterUseOperandIdx(IntB.reg, true);
499   if (UIdx != -1) {
500     ValSEndInst->getOperand(UIdx).setIsKill(false);
501   }
502
503   // Rewrite the copy. If the copy instruction was killing the destination
504   // register before the merge, find the last use and trim the live range. That
505   // will also add the isKill marker.
506   CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
507   if (AS->end == CopyIdx)
508     LIS->shrinkToUses(&IntA);
509
510   ++numExtends;
511   return true;
512 }
513
514 /// hasOtherReachingDefs - Return true if there are definitions of IntB
515 /// other than BValNo val# that can reach uses of AValno val# of IntA.
516 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
517                                              LiveInterval &IntB,
518                                              VNInfo *AValNo,
519                                              VNInfo *BValNo) {
520   // If AValNo has PHI kills, conservatively assume that IntB defs can reach
521   // the PHI values.
522   if (LIS->hasPHIKill(IntA, AValNo))
523     return true;
524
525   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
526        AI != AE; ++AI) {
527     if (AI->valno != AValNo) continue;
528     LiveInterval::iterator BI =
529       std::upper_bound(IntB.begin(), IntB.end(), AI->start);
530     if (BI != IntB.begin())
531       --BI;
532     for (; BI != IntB.end() && AI->end >= BI->start; ++BI) {
533       if (BI->valno == BValNo)
534         continue;
535       if (BI->start <= AI->start && BI->end > AI->start)
536         return true;
537       if (BI->start > AI->start && BI->start < AI->end)
538         return true;
539     }
540   }
541   return false;
542 }
543
544 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy with
545 /// IntA being the source and IntB being the dest, thus this defines a value
546 /// number in IntB.  If the source value number (in IntA) is defined by a
547 /// commutable instruction and its other operand is coalesced to the copy dest
548 /// register, see if we can transform the copy into a noop by commuting the
549 /// definition. For example,
550 ///
551 ///  A3 = op A2 B0<kill>
552 ///    ...
553 ///  B1 = A3      <- this copy
554 ///    ...
555 ///     = op A3   <- more uses
556 ///
557 /// ==>
558 ///
559 ///  B2 = op B0 A2<kill>
560 ///    ...
561 ///  B1 = B2      <- now an identify copy
562 ///    ...
563 ///     = op B2   <- more uses
564 ///
565 /// This returns true if an interval was modified.
566 ///
567 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
568                                                  MachineInstr *CopyMI) {
569   assert (!CP.isPhys());
570
571   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
572
573   LiveInterval &IntA =
574     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
575   LiveInterval &IntB =
576     LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
577
578   // BValNo is a value number in B that is defined by a copy from A. 'B1' in
579   // the example above.
580   VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
581   if (!BValNo || BValNo->def != CopyIdx)
582     return false;
583
584   // AValNo is the value number in A that defines the copy, A3 in the example.
585   VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
586   assert(AValNo && "COPY source not live");
587   if (AValNo->isPHIDef() || AValNo->isUnused())
588     return false;
589   MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
590   if (!DefMI)
591     return false;
592   if (!DefMI->isCommutable())
593     return false;
594   // If DefMI is a two-address instruction then commuting it will change the
595   // destination register.
596   int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
597   assert(DefIdx != -1);
598   unsigned UseOpIdx;
599   if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
600     return false;
601   unsigned Op1, Op2, NewDstIdx;
602   if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
603     return false;
604   if (Op1 == UseOpIdx)
605     NewDstIdx = Op2;
606   else if (Op2 == UseOpIdx)
607     NewDstIdx = Op1;
608   else
609     return false;
610
611   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
612   unsigned NewReg = NewDstMO.getReg();
613   if (NewReg != IntB.reg || !IntB.Query(AValNo->def).isKill())
614     return false;
615
616   // Make sure there are no other definitions of IntB that would reach the
617   // uses which the new definition can reach.
618   if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
619     return false;
620
621   // If some of the uses of IntA.reg is already coalesced away, return false.
622   // It's not possible to determine whether it's safe to perform the coalescing.
623   for (MachineOperand &MO : MRI->use_nodbg_operands(IntA.reg)) {
624     MachineInstr *UseMI = MO.getParent();
625     unsigned OpNo = &MO - &UseMI->getOperand(0);
626     SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
627     LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
628     if (US == IntA.end() || US->valno != AValNo)
629       continue;
630     // If this use is tied to a def, we can't rewrite the register.
631     if (UseMI->isRegTiedToDefOperand(OpNo))
632       return false;
633   }
634
635   DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
636                << *DefMI);
637
638   // At this point we have decided that it is legal to do this
639   // transformation.  Start by commuting the instruction.
640   MachineBasicBlock *MBB = DefMI->getParent();
641   MachineInstr *NewMI = TII->commuteInstruction(DefMI);
642   if (!NewMI)
643     return false;
644   if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
645       TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
646       !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
647     return false;
648   if (NewMI != DefMI) {
649     LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
650     MachineBasicBlock::iterator Pos = DefMI;
651     MBB->insert(Pos, NewMI);
652     MBB->erase(DefMI);
653   }
654   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
655   NewMI->getOperand(OpIdx).setIsKill();
656
657   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
658   // A = or A, B
659   // ...
660   // B = A
661   // ...
662   // C = A<kill>
663   // ...
664   //   = B
665
666   // Update uses of IntA of the specific Val# with IntB.
667   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
668          UE = MRI->use_end(); UI != UE;) {
669     MachineOperand &UseMO = *UI;
670     MachineInstr *UseMI = UseMO.getParent();
671     ++UI;
672     if (UseMI->isDebugValue()) {
673       // FIXME These don't have an instruction index.  Not clear we have enough
674       // info to decide whether to do this replacement or not.  For now do it.
675       UseMO.setReg(NewReg);
676       continue;
677     }
678     SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
679     LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
680     if (US == IntA.end() || US->valno != AValNo)
681       continue;
682     // Kill flags are no longer accurate. They are recomputed after RA.
683     UseMO.setIsKill(false);
684     if (TargetRegisterInfo::isPhysicalRegister(NewReg))
685       UseMO.substPhysReg(NewReg, *TRI);
686     else
687       UseMO.setReg(NewReg);
688     if (UseMI == CopyMI)
689       continue;
690     if (!UseMI->isCopy())
691       continue;
692     if (UseMI->getOperand(0).getReg() != IntB.reg ||
693         UseMI->getOperand(0).getSubReg())
694       continue;
695
696     // This copy will become a noop. If it's defining a new val#, merge it into
697     // BValNo.
698     SlotIndex DefIdx = UseIdx.getRegSlot();
699     VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
700     if (!DVNI)
701       continue;
702     DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
703     assert(DVNI->def == DefIdx);
704     BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
705     ErasedInstrs.insert(UseMI);
706     LIS->RemoveMachineInstrFromMaps(UseMI);
707     UseMI->eraseFromParent();
708   }
709
710   // Extend BValNo by merging in IntA live segments of AValNo. Val# definition
711   // is updated.
712   VNInfo *ValNo = BValNo;
713   ValNo->def = AValNo->def;
714   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
715        AI != AE; ++AI) {
716     if (AI->valno != AValNo) continue;
717     IntB.addSegment(LiveInterval::Segment(AI->start, AI->end, ValNo));
718   }
719   DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
720
721   IntA.removeValNo(AValNo);
722   DEBUG(dbgs() << "\t\ttrimmed:  " << IntA << '\n');
723   ++numCommutes;
724   return true;
725 }
726
727 /// reMaterializeTrivialDef - If the source of a copy is defined by a trivial
728 /// computation, replace the copy by rematerialize the definition.
729 bool RegisterCoalescer::reMaterializeTrivialDef(CoalescerPair &CP,
730                                                 MachineInstr *CopyMI,
731                                                 bool &IsDefCopy) {
732   IsDefCopy = false;
733   unsigned SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg();
734   unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx();
735   unsigned DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
736   unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx();
737   if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
738     return false;
739
740   LiveInterval &SrcInt = LIS->getInterval(SrcReg);
741   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI);
742   VNInfo *ValNo = SrcInt.Query(CopyIdx).valueIn();
743   assert(ValNo && "CopyMI input register not live");
744   if (ValNo->isPHIDef() || ValNo->isUnused())
745     return false;
746   MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
747   if (!DefMI)
748     return false;
749   if (DefMI->isCopyLike()) {
750     IsDefCopy = true;
751     return false;
752   }
753   if (!DefMI->isAsCheapAsAMove())
754     return false;
755   if (!TII->isTriviallyReMaterializable(DefMI, AA))
756     return false;
757   bool SawStore = false;
758   if (!DefMI->isSafeToMove(TII, AA, SawStore))
759     return false;
760   const MCInstrDesc &MCID = DefMI->getDesc();
761   if (MCID.getNumDefs() != 1)
762     return false;
763   // Only support subregister destinations when the def is read-undef.
764   MachineOperand &DstOperand = CopyMI->getOperand(0);
765   unsigned CopyDstReg = DstOperand.getReg();
766   if (DstOperand.getSubReg() && !DstOperand.isUndef())
767     return false;
768
769   // If both SrcIdx and DstIdx are set, correct rematerialization would widen
770   // the register substantially (beyond both source and dest size). This is bad
771   // for performance since it can cascade through a function, introducing many
772   // extra spills and fills (e.g. ARM can easily end up copying QQQQPR registers
773   // around after a few subreg copies).
774   if (SrcIdx && DstIdx)
775     return false;
776
777   const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0, TRI, *MF);
778   if (!DefMI->isImplicitDef()) {
779     if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
780       unsigned NewDstReg = DstReg;
781
782       unsigned NewDstIdx = TRI->composeSubRegIndices(CP.getSrcIdx(),
783                                               DefMI->getOperand(0).getSubReg());
784       if (NewDstIdx)
785         NewDstReg = TRI->getSubReg(DstReg, NewDstIdx);
786
787       // Finally, make sure that the physical subregister that will be
788       // constructed later is permitted for the instruction.
789       if (!DefRC->contains(NewDstReg))
790         return false;
791     } else {
792       // Theoretically, some stack frame reference could exist. Just make sure
793       // it hasn't actually happened.
794       assert(TargetRegisterInfo::isVirtualRegister(DstReg) &&
795              "Only expect to deal with virtual or physical registers");
796     }
797   }
798
799   MachineBasicBlock *MBB = CopyMI->getParent();
800   MachineBasicBlock::iterator MII =
801     std::next(MachineBasicBlock::iterator(CopyMI));
802   TII->reMaterialize(*MBB, MII, DstReg, SrcIdx, DefMI, *TRI);
803   MachineInstr *NewMI = std::prev(MII);
804
805   LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
806   CopyMI->eraseFromParent();
807   ErasedInstrs.insert(CopyMI);
808
809   // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
810   // We need to remember these so we can add intervals once we insert
811   // NewMI into SlotIndexes.
812   SmallVector<unsigned, 4> NewMIImplDefs;
813   for (unsigned i = NewMI->getDesc().getNumOperands(),
814          e = NewMI->getNumOperands(); i != e; ++i) {
815     MachineOperand &MO = NewMI->getOperand(i);
816     if (MO.isReg()) {
817       assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
818              TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
819       NewMIImplDefs.push_back(MO.getReg());
820     }
821   }
822
823   if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
824     const TargetRegisterClass *NewRC = CP.getNewRC();
825     unsigned NewIdx = NewMI->getOperand(0).getSubReg();
826
827     if (NewIdx)
828       NewRC = TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx);
829     else
830       NewRC = TRI->getCommonSubClass(NewRC, DefRC);
831
832     assert(NewRC && "subreg chosen for remat incompatible with instruction");
833     MRI->setRegClass(DstReg, NewRC);
834
835     updateRegDefsUses(DstReg, DstReg, DstIdx);
836     NewMI->getOperand(0).setSubReg(NewIdx);
837   } else if (NewMI->getOperand(0).getReg() != CopyDstReg) {
838     // The New instruction may be defining a sub-register of what's actually
839     // been asked for. If so it must implicitly define the whole thing.
840     assert(TargetRegisterInfo::isPhysicalRegister(DstReg) &&
841            "Only expect virtual or physical registers in remat");
842     NewMI->getOperand(0).setIsDead(true);
843     NewMI->addOperand(MachineOperand::CreateReg(CopyDstReg,
844                                                 true  /*IsDef*/,
845                                                 true  /*IsImp*/,
846                                                 false /*IsKill*/));
847     // Record small dead def live-ranges for all the subregisters
848     // of the destination register.
849     // Otherwise, variables that live through may miss some
850     // interferences, thus creating invalid allocation.
851     // E.g., i386 code:
852     // vreg1 = somedef ; vreg1 GR8
853     // vreg2 = remat ; vreg2 GR32
854     // CL = COPY vreg2.sub_8bit
855     // = somedef vreg1 ; vreg1 GR8
856     // =>
857     // vreg1 = somedef ; vreg1 GR8
858     // ECX<def, dead> = remat ; CL<imp-def>
859     // = somedef vreg1 ; vreg1 GR8
860     // vreg1 will see the inteferences with CL but not with CH since
861     // no live-ranges would have been created for ECX.
862     // Fix that!
863     SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
864     for (MCRegUnitIterator Units(NewMI->getOperand(0).getReg(), TRI);
865          Units.isValid(); ++Units)
866       if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
867         LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
868   }
869
870   if (NewMI->getOperand(0).getSubReg())
871     NewMI->getOperand(0).setIsUndef();
872
873   // CopyMI may have implicit operands, transfer them over to the newly
874   // rematerialized instruction. And update implicit def interval valnos.
875   for (unsigned i = CopyMI->getDesc().getNumOperands(),
876          e = CopyMI->getNumOperands(); i != e; ++i) {
877     MachineOperand &MO = CopyMI->getOperand(i);
878     if (MO.isReg()) {
879       assert(MO.isImplicit() && "No explicit operands after implict operands.");
880       // Discard VReg implicit defs.
881       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
882         NewMI->addOperand(MO);
883       }
884     }
885   }
886
887   SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
888   for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
889     unsigned Reg = NewMIImplDefs[i];
890     for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
891       if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
892         LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
893   }
894
895   DEBUG(dbgs() << "Remat: " << *NewMI);
896   ++NumReMats;
897
898   // The source interval can become smaller because we removed a use.
899   LIS->shrinkToUses(&SrcInt, &DeadDefs);
900   if (!DeadDefs.empty())
901     eliminateDeadDefs();
902
903   return true;
904 }
905
906 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
907 /// values, it only removes local variables. When we have a copy like:
908 ///
909 ///   %vreg1 = COPY %vreg2<undef>
910 ///
911 /// We delete the copy and remove the corresponding value number from %vreg1.
912 /// Any uses of that value number are marked as <undef>.
913 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
914                                            const CoalescerPair &CP) {
915   SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
916   LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
917   if (SrcInt->liveAt(Idx))
918     return false;
919   LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
920   if (DstInt->liveAt(Idx))
921     return false;
922
923   // No intervals are live-in to CopyMI - it is undef.
924   if (CP.isFlipped())
925     DstInt = SrcInt;
926   SrcInt = 0;
927
928   VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
929   assert(DeadVNI && "No value defined in DstInt");
930   DstInt->removeValNo(DeadVNI);
931
932   // Find new undef uses.
933   for (MachineOperand &MO : MRI->reg_nodbg_operands(DstInt->reg)) {
934     if (MO.isDef() || MO.isUndef())
935       continue;
936     MachineInstr *MI = MO.getParent();
937     SlotIndex Idx = LIS->getInstructionIndex(MI);
938     if (DstInt->liveAt(Idx))
939       continue;
940     MO.setIsUndef(true);
941     DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
942   }
943   return true;
944 }
945
946 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
947 /// update the subregister number if it is not zero. If DstReg is a
948 /// physical register and the existing subregister number of the def / use
949 /// being updated is not zero, make sure to set it to the correct physical
950 /// subregister.
951 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
952                                           unsigned DstReg,
953                                           unsigned SubIdx) {
954   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
955   LiveInterval *DstInt = DstIsPhys ? 0 : &LIS->getInterval(DstReg);
956
957   SmallPtrSet<MachineInstr*, 8> Visited;
958   for (MachineRegisterInfo::reg_instr_iterator
959        I = MRI->reg_instr_begin(SrcReg), E = MRI->reg_instr_end();
960        I != E; ) {
961     MachineInstr *UseMI = &*(I++);
962
963     // Each instruction can only be rewritten once because sub-register
964     // composition is not always idempotent. When SrcReg != DstReg, rewriting
965     // the UseMI operands removes them from the SrcReg use-def chain, but when
966     // SrcReg is DstReg we could encounter UseMI twice if it has multiple
967     // operands mentioning the virtual register.
968     if (SrcReg == DstReg && !Visited.insert(UseMI))
969       continue;
970
971     SmallVector<unsigned,8> Ops;
972     bool Reads, Writes;
973     std::tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
974
975     // If SrcReg wasn't read, it may still be the case that DstReg is live-in
976     // because SrcReg is a sub-register.
977     if (DstInt && !Reads && SubIdx)
978       Reads = DstInt->liveAt(LIS->getInstructionIndex(UseMI));
979
980     // Replace SrcReg with DstReg in all UseMI operands.
981     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
982       MachineOperand &MO = UseMI->getOperand(Ops[i]);
983
984       // Adjust <undef> flags in case of sub-register joins. We don't want to
985       // turn a full def into a read-modify-write sub-register def and vice
986       // versa.
987       if (SubIdx && MO.isDef())
988         MO.setIsUndef(!Reads);
989
990       if (DstIsPhys)
991         MO.substPhysReg(DstReg, *TRI);
992       else
993         MO.substVirtReg(DstReg, SubIdx, *TRI);
994     }
995
996     DEBUG({
997         dbgs() << "\t\tupdated: ";
998         if (!UseMI->isDebugValue())
999           dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
1000         dbgs() << *UseMI;
1001       });
1002   }
1003 }
1004
1005 /// canJoinPhys - Return true if a copy involving a physreg should be joined.
1006 bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) {
1007   /// Always join simple intervals that are defined by a single copy from a
1008   /// reserved register. This doesn't increase register pressure, so it is
1009   /// always beneficial.
1010   if (!MRI->isReserved(CP.getDstReg())) {
1011     DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
1012     return false;
1013   }
1014
1015   LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1016   if (CP.isFlipped() && JoinVInt.containsOneValue())
1017     return true;
1018
1019   DEBUG(dbgs() << "\tCannot join defs into reserved register.\n");
1020   return false;
1021 }
1022
1023 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1024 /// which are the src/dst of the copy instruction CopyMI.  This returns true
1025 /// if the copy was successfully coalesced away. If it is not currently
1026 /// possible to coalesce this interval, but it may be possible if other
1027 /// things get coalesced, then it returns true by reference in 'Again'.
1028 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
1029
1030   Again = false;
1031   DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1032
1033   CoalescerPair CP(*TRI);
1034   if (!CP.setRegisters(CopyMI)) {
1035     DEBUG(dbgs() << "\tNot coalescable.\n");
1036     return false;
1037   }
1038
1039   // Dead code elimination. This really should be handled by MachineDCE, but
1040   // sometimes dead copies slip through, and we can't generate invalid live
1041   // ranges.
1042   if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
1043     DEBUG(dbgs() << "\tCopy is dead.\n");
1044     DeadDefs.push_back(CopyMI);
1045     eliminateDeadDefs();
1046     return true;
1047   }
1048
1049   // Eliminate undefs.
1050   if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
1051     DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
1052     LIS->RemoveMachineInstrFromMaps(CopyMI);
1053     CopyMI->eraseFromParent();
1054     return false;  // Not coalescable.
1055   }
1056
1057   // Coalesced copies are normally removed immediately, but transformations
1058   // like removeCopyByCommutingDef() can inadvertently create identity copies.
1059   // When that happens, just join the values and remove the copy.
1060   if (CP.getSrcReg() == CP.getDstReg()) {
1061     LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
1062     DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
1063     LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(CopyMI));
1064     if (VNInfo *DefVNI = LRQ.valueDefined()) {
1065       VNInfo *ReadVNI = LRQ.valueIn();
1066       assert(ReadVNI && "No value before copy and no <undef> flag.");
1067       assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
1068       LI.MergeValueNumberInto(DefVNI, ReadVNI);
1069       DEBUG(dbgs() << "\tMerged values:          " << LI << '\n');
1070     }
1071     LIS->RemoveMachineInstrFromMaps(CopyMI);
1072     CopyMI->eraseFromParent();
1073     return true;
1074   }
1075
1076   // Enforce policies.
1077   if (CP.isPhys()) {
1078     DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1079                  << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
1080                  << '\n');
1081     if (!canJoinPhys(CP)) {
1082       // Before giving up coalescing, if definition of source is defined by
1083       // trivial computation, try rematerializing it.
1084       bool IsDefCopy;
1085       if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1086         return true;
1087       if (IsDefCopy)
1088         Again = true;  // May be possible to coalesce later.
1089       return false;
1090     }
1091   } else {
1092     DEBUG({
1093       dbgs() << "\tConsidering merging to " << CP.getNewRC()->getName()
1094              << " with ";
1095       if (CP.getDstIdx() && CP.getSrcIdx())
1096         dbgs() << PrintReg(CP.getDstReg()) << " in "
1097                << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
1098                << PrintReg(CP.getSrcReg()) << " in "
1099                << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
1100       else
1101         dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
1102                << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
1103     });
1104
1105     // When possible, let DstReg be the larger interval.
1106     if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).size() >
1107                            LIS->getInterval(CP.getDstReg()).size())
1108       CP.flip();
1109   }
1110
1111   // Okay, attempt to join these two intervals.  On failure, this returns false.
1112   // Otherwise, if one of the intervals being joined is a physreg, this method
1113   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1114   // been modified, so we can use this information below to update aliases.
1115   if (!joinIntervals(CP)) {
1116     // Coalescing failed.
1117
1118     // If definition of source is defined by trivial computation, try
1119     // rematerializing it.
1120     bool IsDefCopy;
1121     if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1122       return true;
1123
1124     // If we can eliminate the copy without merging the live segments, do so
1125     // now.
1126     if (!CP.isPartial() && !CP.isPhys()) {
1127       if (adjustCopiesBackFrom(CP, CopyMI) ||
1128           removeCopyByCommutingDef(CP, CopyMI)) {
1129         LIS->RemoveMachineInstrFromMaps(CopyMI);
1130         CopyMI->eraseFromParent();
1131         DEBUG(dbgs() << "\tTrivial!\n");
1132         return true;
1133       }
1134     }
1135
1136     // Otherwise, we are unable to join the intervals.
1137     DEBUG(dbgs() << "\tInterference!\n");
1138     Again = true;  // May be possible to coalesce later.
1139     return false;
1140   }
1141
1142   // Coalescing to a virtual register that is of a sub-register class of the
1143   // other. Make sure the resulting register is set to the right register class.
1144   if (CP.isCrossClass()) {
1145     ++numCrossRCs;
1146     MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1147   }
1148
1149   // Removing sub-register copies can ease the register class constraints.
1150   // Make sure we attempt to inflate the register class of DstReg.
1151   if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
1152     InflateRegs.push_back(CP.getDstReg());
1153
1154   // CopyMI has been erased by joinIntervals at this point. Remove it from
1155   // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
1156   // to the work list. This keeps ErasedInstrs from growing needlessly.
1157   ErasedInstrs.erase(CopyMI);
1158
1159   // Rewrite all SrcReg operands to DstReg.
1160   // Also update DstReg operands to include DstIdx if it is set.
1161   if (CP.getDstIdx())
1162     updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1163   updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1164
1165   // SrcReg is guaranteed to be the register whose live interval that is
1166   // being merged.
1167   LIS->removeInterval(CP.getSrcReg());
1168
1169   // Update regalloc hint.
1170   TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1171
1172   DEBUG({
1173     dbgs() << "\tJoined. Result = ";
1174     if (CP.isPhys())
1175       dbgs() << PrintReg(CP.getDstReg(), TRI);
1176     else
1177       dbgs() << LIS->getInterval(CP.getDstReg());
1178     dbgs() << '\n';
1179   });
1180
1181   ++numJoins;
1182   return true;
1183 }
1184
1185 /// Attempt joining with a reserved physreg.
1186 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1187   assert(CP.isPhys() && "Must be a physreg copy");
1188   assert(MRI->isReserved(CP.getDstReg()) && "Not a reserved register");
1189   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1190   DEBUG(dbgs() << "\t\tRHS = " << RHS << '\n');
1191
1192   assert(CP.isFlipped() && RHS.containsOneValue() &&
1193          "Invalid join with reserved register");
1194
1195   // Optimization for reserved registers like ESP. We can only merge with a
1196   // reserved physreg if RHS has a single value that is a copy of CP.DstReg().
1197   // The live range of the reserved register will look like a set of dead defs
1198   // - we don't properly track the live range of reserved registers.
1199
1200   // Deny any overlapping intervals.  This depends on all the reserved
1201   // register live ranges to look like dead defs.
1202   for (MCRegUnitIterator UI(CP.getDstReg(), TRI); UI.isValid(); ++UI)
1203     if (RHS.overlaps(LIS->getRegUnit(*UI))) {
1204       DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n');
1205       return false;
1206     }
1207
1208   // Skip any value computations, we are not adding new values to the
1209   // reserved register.  Also skip merging the live ranges, the reserved
1210   // register live range doesn't need to be accurate as long as all the
1211   // defs are there.
1212
1213   // Delete the identity copy.
1214   MachineInstr *CopyMI = MRI->getVRegDef(RHS.reg);
1215   LIS->RemoveMachineInstrFromMaps(CopyMI);
1216   CopyMI->eraseFromParent();
1217
1218   // We don't track kills for reserved registers.
1219   MRI->clearKillFlags(CP.getSrcReg());
1220
1221   return true;
1222 }
1223
1224 //===----------------------------------------------------------------------===//
1225 //                 Interference checking and interval joining
1226 //===----------------------------------------------------------------------===//
1227 //
1228 // In the easiest case, the two live ranges being joined are disjoint, and
1229 // there is no interference to consider. It is quite common, though, to have
1230 // overlapping live ranges, and we need to check if the interference can be
1231 // resolved.
1232 //
1233 // The live range of a single SSA value forms a sub-tree of the dominator tree.
1234 // This means that two SSA values overlap if and only if the def of one value
1235 // is contained in the live range of the other value. As a special case, the
1236 // overlapping values can be defined at the same index.
1237 //
1238 // The interference from an overlapping def can be resolved in these cases:
1239 //
1240 // 1. Coalescable copies. The value is defined by a copy that would become an
1241 //    identity copy after joining SrcReg and DstReg. The copy instruction will
1242 //    be removed, and the value will be merged with the source value.
1243 //
1244 //    There can be several copies back and forth, causing many values to be
1245 //    merged into one. We compute a list of ultimate values in the joined live
1246 //    range as well as a mappings from the old value numbers.
1247 //
1248 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
1249 //    predecessors have a live out value. It doesn't cause real interference,
1250 //    and can be merged into the value it overlaps. Like a coalescable copy, it
1251 //    can be erased after joining.
1252 //
1253 // 3. Copy of external value. The overlapping def may be a copy of a value that
1254 //    is already in the other register. This is like a coalescable copy, but
1255 //    the live range of the source register must be trimmed after erasing the
1256 //    copy instruction:
1257 //
1258 //      %src = COPY %ext
1259 //      %dst = COPY %ext  <-- Remove this COPY, trim the live range of %ext.
1260 //
1261 // 4. Clobbering undefined lanes. Vector registers are sometimes built by
1262 //    defining one lane at a time:
1263 //
1264 //      %dst:ssub0<def,read-undef> = FOO
1265 //      %src = BAR
1266 //      %dst:ssub1<def> = COPY %src
1267 //
1268 //    The live range of %src overlaps the %dst value defined by FOO, but
1269 //    merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
1270 //    which was undef anyway.
1271 //
1272 //    The value mapping is more complicated in this case. The final live range
1273 //    will have different value numbers for both FOO and BAR, but there is no
1274 //    simple mapping from old to new values. It may even be necessary to add
1275 //    new PHI values.
1276 //
1277 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
1278 //    is live, but never read. This can happen because we don't compute
1279 //    individual live ranges per lane.
1280 //
1281 //      %dst<def> = FOO
1282 //      %src = BAR
1283 //      %dst:ssub1<def> = COPY %src
1284 //
1285 //    This kind of interference is only resolved locally. If the clobbered
1286 //    lane value escapes the block, the join is aborted.
1287
1288 namespace {
1289 /// Track information about values in a single virtual register about to be
1290 /// joined. Objects of this class are always created in pairs - one for each
1291 /// side of the CoalescerPair.
1292 class JoinVals {
1293   LiveInterval &LI;
1294
1295   // Location of this register in the final joined register.
1296   // Either CP.DstIdx or CP.SrcIdx.
1297   unsigned SubIdx;
1298
1299   // Values that will be present in the final live range.
1300   SmallVectorImpl<VNInfo*> &NewVNInfo;
1301
1302   const CoalescerPair &CP;
1303   LiveIntervals *LIS;
1304   SlotIndexes *Indexes;
1305   const TargetRegisterInfo *TRI;
1306
1307   // Value number assignments. Maps value numbers in LI to entries in NewVNInfo.
1308   // This is suitable for passing to LiveInterval::join().
1309   SmallVector<int, 8> Assignments;
1310
1311   // Conflict resolution for overlapping values.
1312   enum ConflictResolution {
1313     // No overlap, simply keep this value.
1314     CR_Keep,
1315
1316     // Merge this value into OtherVNI and erase the defining instruction.
1317     // Used for IMPLICIT_DEF, coalescable copies, and copies from external
1318     // values.
1319     CR_Erase,
1320
1321     // Merge this value into OtherVNI but keep the defining instruction.
1322     // This is for the special case where OtherVNI is defined by the same
1323     // instruction.
1324     CR_Merge,
1325
1326     // Keep this value, and have it replace OtherVNI where possible. This
1327     // complicates value mapping since OtherVNI maps to two different values
1328     // before and after this def.
1329     // Used when clobbering undefined or dead lanes.
1330     CR_Replace,
1331
1332     // Unresolved conflict. Visit later when all values have been mapped.
1333     CR_Unresolved,
1334
1335     // Unresolvable conflict. Abort the join.
1336     CR_Impossible
1337   };
1338
1339   // Per-value info for LI. The lane bit masks are all relative to the final
1340   // joined register, so they can be compared directly between SrcReg and
1341   // DstReg.
1342   struct Val {
1343     ConflictResolution Resolution;
1344
1345     // Lanes written by this def, 0 for unanalyzed values.
1346     unsigned WriteLanes;
1347
1348     // Lanes with defined values in this register. Other lanes are undef and
1349     // safe to clobber.
1350     unsigned ValidLanes;
1351
1352     // Value in LI being redefined by this def.
1353     VNInfo *RedefVNI;
1354
1355     // Value in the other live range that overlaps this def, if any.
1356     VNInfo *OtherVNI;
1357
1358     // Is this value an IMPLICIT_DEF that can be erased?
1359     //
1360     // IMPLICIT_DEF values should only exist at the end of a basic block that
1361     // is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be
1362     // safely erased if they are overlapping a live value in the other live
1363     // interval.
1364     //
1365     // Weird control flow graphs and incomplete PHI handling in
1366     // ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with
1367     // longer live ranges. Such IMPLICIT_DEF values should be treated like
1368     // normal values.
1369     bool ErasableImplicitDef;
1370
1371     // True when the live range of this value will be pruned because of an
1372     // overlapping CR_Replace value in the other live range.
1373     bool Pruned;
1374
1375     // True once Pruned above has been computed.
1376     bool PrunedComputed;
1377
1378     Val() : Resolution(CR_Keep), WriteLanes(0), ValidLanes(0),
1379             RedefVNI(0), OtherVNI(0), ErasableImplicitDef(false),
1380             Pruned(false), PrunedComputed(false) {}
1381
1382     bool isAnalyzed() const { return WriteLanes != 0; }
1383   };
1384
1385   // One entry per value number in LI.
1386   SmallVector<Val, 8> Vals;
1387
1388   unsigned computeWriteLanes(const MachineInstr *DefMI, bool &Redef);
1389   VNInfo *stripCopies(VNInfo *VNI);
1390   ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
1391   void computeAssignment(unsigned ValNo, JoinVals &Other);
1392   bool taintExtent(unsigned, unsigned, JoinVals&,
1393                    SmallVectorImpl<std::pair<SlotIndex, unsigned> >&);
1394   bool usesLanes(MachineInstr *MI, unsigned, unsigned, unsigned);
1395   bool isPrunedValue(unsigned ValNo, JoinVals &Other);
1396
1397 public:
1398   JoinVals(LiveInterval &li, unsigned subIdx,
1399            SmallVectorImpl<VNInfo*> &newVNInfo,
1400            const CoalescerPair &cp,
1401            LiveIntervals *lis,
1402            const TargetRegisterInfo *tri)
1403     : LI(li), SubIdx(subIdx), NewVNInfo(newVNInfo), CP(cp), LIS(lis),
1404       Indexes(LIS->getSlotIndexes()), TRI(tri),
1405       Assignments(LI.getNumValNums(), -1), Vals(LI.getNumValNums())
1406   {}
1407
1408   /// Analyze defs in LI and compute a value mapping in NewVNInfo.
1409   /// Returns false if any conflicts were impossible to resolve.
1410   bool mapValues(JoinVals &Other);
1411
1412   /// Try to resolve conflicts that require all values to be mapped.
1413   /// Returns false if any conflicts were impossible to resolve.
1414   bool resolveConflicts(JoinVals &Other);
1415
1416   /// Prune the live range of values in Other.LI where they would conflict with
1417   /// CR_Replace values in LI. Collect end points for restoring the live range
1418   /// after joining.
1419   void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints);
1420
1421   /// Erase any machine instructions that have been coalesced away.
1422   /// Add erased instructions to ErasedInstrs.
1423   /// Add foreign virtual registers to ShrinkRegs if their live range ended at
1424   /// the erased instrs.
1425   void eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs,
1426                    SmallVectorImpl<unsigned> &ShrinkRegs);
1427
1428   /// Get the value assignments suitable for passing to LiveInterval::join.
1429   const int *getAssignments() const { return Assignments.data(); }
1430 };
1431 } // end anonymous namespace
1432
1433 /// Compute the bitmask of lanes actually written by DefMI.
1434 /// Set Redef if there are any partial register definitions that depend on the
1435 /// previous value of the register.
1436 unsigned JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef) {
1437   unsigned L = 0;
1438   for (ConstMIOperands MO(DefMI); MO.isValid(); ++MO) {
1439     if (!MO->isReg() || MO->getReg() != LI.reg || !MO->isDef())
1440       continue;
1441     L |= TRI->getSubRegIndexLaneMask(
1442            TRI->composeSubRegIndices(SubIdx, MO->getSubReg()));
1443     if (MO->readsReg())
1444       Redef = true;
1445   }
1446   return L;
1447 }
1448
1449 /// Find the ultimate value that VNI was copied from.
1450 VNInfo *JoinVals::stripCopies(VNInfo *VNI) {
1451   while (!VNI->isPHIDef()) {
1452     MachineInstr *MI = Indexes->getInstructionFromIndex(VNI->def);
1453     assert(MI && "No defining instruction");
1454     if (!MI->isFullCopy())
1455       break;
1456     unsigned Reg = MI->getOperand(1).getReg();
1457     if (!TargetRegisterInfo::isVirtualRegister(Reg))
1458       break;
1459     LiveQueryResult LRQ = LIS->getInterval(Reg).Query(VNI->def);
1460     if (!LRQ.valueIn())
1461       break;
1462     VNI = LRQ.valueIn();
1463   }
1464   return VNI;
1465 }
1466
1467 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
1468 /// Return a conflict resolution when possible, but leave the hard cases as
1469 /// CR_Unresolved.
1470 /// Recursively calls computeAssignment() on this and Other, guaranteeing that
1471 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
1472 /// The recursion always goes upwards in the dominator tree, making loops
1473 /// impossible.
1474 JoinVals::ConflictResolution
1475 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
1476   Val &V = Vals[ValNo];
1477   assert(!V.isAnalyzed() && "Value has already been analyzed!");
1478   VNInfo *VNI = LI.getValNumInfo(ValNo);
1479   if (VNI->isUnused()) {
1480     V.WriteLanes = ~0u;
1481     return CR_Keep;
1482   }
1483
1484   // Get the instruction defining this value, compute the lanes written.
1485   const MachineInstr *DefMI = 0;
1486   if (VNI->isPHIDef()) {
1487     // Conservatively assume that all lanes in a PHI are valid.
1488     V.ValidLanes = V.WriteLanes = TRI->getSubRegIndexLaneMask(SubIdx);
1489   } else {
1490     DefMI = Indexes->getInstructionFromIndex(VNI->def);
1491     bool Redef = false;
1492     V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
1493
1494     // If this is a read-modify-write instruction, there may be more valid
1495     // lanes than the ones written by this instruction.
1496     // This only covers partial redef operands. DefMI may have normal use
1497     // operands reading the register. They don't contribute valid lanes.
1498     //
1499     // This adds ssub1 to the set of valid lanes in %src:
1500     //
1501     //   %src:ssub1<def> = FOO
1502     //
1503     // This leaves only ssub1 valid, making any other lanes undef:
1504     //
1505     //   %src:ssub1<def,read-undef> = FOO %src:ssub2
1506     //
1507     // The <read-undef> flag on the def operand means that old lane values are
1508     // not important.
1509     if (Redef) {
1510       V.RedefVNI = LI.Query(VNI->def).valueIn();
1511       assert(V.RedefVNI && "Instruction is reading nonexistent value");
1512       computeAssignment(V.RedefVNI->id, Other);
1513       V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
1514     }
1515
1516     // An IMPLICIT_DEF writes undef values.
1517     if (DefMI->isImplicitDef()) {
1518       // We normally expect IMPLICIT_DEF values to be live only until the end
1519       // of their block. If the value is really live longer and gets pruned in
1520       // another block, this flag is cleared again.
1521       V.ErasableImplicitDef = true;
1522       V.ValidLanes &= ~V.WriteLanes;
1523     }
1524   }
1525
1526   // Find the value in Other that overlaps VNI->def, if any.
1527   LiveQueryResult OtherLRQ = Other.LI.Query(VNI->def);
1528
1529   // It is possible that both values are defined by the same instruction, or
1530   // the values are PHIs defined in the same block. When that happens, the two
1531   // values should be merged into one, but not into any preceding value.
1532   // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
1533   if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
1534     assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
1535
1536     // One value stays, the other is merged. Keep the earlier one, or the first
1537     // one we see.
1538     if (OtherVNI->def < VNI->def)
1539       Other.computeAssignment(OtherVNI->id, *this);
1540     else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
1541       // This is an early-clobber def overlapping a live-in value in the other
1542       // register. Not mergeable.
1543       V.OtherVNI = OtherLRQ.valueIn();
1544       return CR_Impossible;
1545     }
1546     V.OtherVNI = OtherVNI;
1547     Val &OtherV = Other.Vals[OtherVNI->id];
1548     // Keep this value, check for conflicts when analyzing OtherVNI.
1549     if (!OtherV.isAnalyzed())
1550       return CR_Keep;
1551     // Both sides have been analyzed now.
1552     // Allow overlapping PHI values. Any real interference would show up in a
1553     // predecessor, the PHI itself can't introduce any conflicts.
1554     if (VNI->isPHIDef())
1555       return CR_Merge;
1556     if (V.ValidLanes & OtherV.ValidLanes)
1557       // Overlapping lanes can't be resolved.
1558       return CR_Impossible;
1559     else
1560       return CR_Merge;
1561   }
1562
1563   // No simultaneous def. Is Other live at the def?
1564   V.OtherVNI = OtherLRQ.valueIn();
1565   if (!V.OtherVNI)
1566     // No overlap, no conflict.
1567     return CR_Keep;
1568
1569   assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
1570
1571   // We have overlapping values, or possibly a kill of Other.
1572   // Recursively compute assignments up the dominator tree.
1573   Other.computeAssignment(V.OtherVNI->id, *this);
1574   Val &OtherV = Other.Vals[V.OtherVNI->id];
1575
1576   // Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block.
1577   // This shouldn't normally happen, but ProcessImplicitDefs can leave such
1578   // IMPLICIT_DEF instructions behind, and there is nothing wrong with it
1579   // technically.
1580   //
1581   // WHen it happens, treat that IMPLICIT_DEF as a normal value, and don't try
1582   // to erase the IMPLICIT_DEF instruction.
1583   if (OtherV.ErasableImplicitDef && DefMI &&
1584       DefMI->getParent() != Indexes->getMBBFromIndex(V.OtherVNI->def)) {
1585     DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def
1586                  << " extends into BB#" << DefMI->getParent()->getNumber()
1587                  << ", keeping it.\n");
1588     OtherV.ErasableImplicitDef = false;
1589   }
1590
1591   // Allow overlapping PHI values. Any real interference would show up in a
1592   // predecessor, the PHI itself can't introduce any conflicts.
1593   if (VNI->isPHIDef())
1594     return CR_Replace;
1595
1596   // Check for simple erasable conflicts.
1597   if (DefMI->isImplicitDef())
1598     return CR_Erase;
1599
1600   // Include the non-conflict where DefMI is a coalescable copy that kills
1601   // OtherVNI. We still want the copy erased and value numbers merged.
1602   if (CP.isCoalescable(DefMI)) {
1603     // Some of the lanes copied from OtherVNI may be undef, making them undef
1604     // here too.
1605     V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
1606     return CR_Erase;
1607   }
1608
1609   // This may not be a real conflict if DefMI simply kills Other and defines
1610   // VNI.
1611   if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
1612     return CR_Keep;
1613
1614   // Handle the case where VNI and OtherVNI can be proven to be identical:
1615   //
1616   //   %other = COPY %ext
1617   //   %this  = COPY %ext <-- Erase this copy
1618   //
1619   if (DefMI->isFullCopy() && !CP.isPartial() &&
1620       stripCopies(VNI) == stripCopies(V.OtherVNI))
1621     return CR_Erase;
1622
1623   // If the lanes written by this instruction were all undef in OtherVNI, it is
1624   // still safe to join the live ranges. This can't be done with a simple value
1625   // mapping, though - OtherVNI will map to multiple values:
1626   //
1627   //   1 %dst:ssub0 = FOO                <-- OtherVNI
1628   //   2 %src = BAR                      <-- VNI
1629   //   3 %dst:ssub1 = COPY %src<kill>    <-- Eliminate this copy.
1630   //   4 BAZ %dst<kill>
1631   //   5 QUUX %src<kill>
1632   //
1633   // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
1634   // handles this complex value mapping.
1635   if ((V.WriteLanes & OtherV.ValidLanes) == 0)
1636     return CR_Replace;
1637
1638   // If the other live range is killed by DefMI and the live ranges are still
1639   // overlapping, it must be because we're looking at an early clobber def:
1640   //
1641   //   %dst<def,early-clobber> = ASM %src<kill>
1642   //
1643   // In this case, it is illegal to merge the two live ranges since the early
1644   // clobber def would clobber %src before it was read.
1645   if (OtherLRQ.isKill()) {
1646     // This case where the def doesn't overlap the kill is handled above.
1647     assert(VNI->def.isEarlyClobber() &&
1648            "Only early clobber defs can overlap a kill");
1649     return CR_Impossible;
1650   }
1651
1652   // VNI is clobbering live lanes in OtherVNI, but there is still the
1653   // possibility that no instructions actually read the clobbered lanes.
1654   // If we're clobbering all the lanes in OtherVNI, at least one must be read.
1655   // Otherwise Other.LI wouldn't be live here.
1656   if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes) == 0)
1657     return CR_Impossible;
1658
1659   // We need to verify that no instructions are reading the clobbered lanes. To
1660   // save compile time, we'll only check that locally. Don't allow the tainted
1661   // value to escape the basic block.
1662   MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1663   if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
1664     return CR_Impossible;
1665
1666   // There are still some things that could go wrong besides clobbered lanes
1667   // being read, for example OtherVNI may be only partially redefined in MBB,
1668   // and some clobbered lanes could escape the block. Save this analysis for
1669   // resolveConflicts() when all values have been mapped. We need to know
1670   // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
1671   // that now - the recursive analyzeValue() calls must go upwards in the
1672   // dominator tree.
1673   return CR_Unresolved;
1674 }
1675
1676 /// Compute the value assignment for ValNo in LI.
1677 /// This may be called recursively by analyzeValue(), but never for a ValNo on
1678 /// the stack.
1679 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
1680   Val &V = Vals[ValNo];
1681   if (V.isAnalyzed()) {
1682     // Recursion should always move up the dominator tree, so ValNo is not
1683     // supposed to reappear before it has been assigned.
1684     assert(Assignments[ValNo] != -1 && "Bad recursion?");
1685     return;
1686   }
1687   switch ((V.Resolution = analyzeValue(ValNo, Other))) {
1688   case CR_Erase:
1689   case CR_Merge:
1690     // Merge this ValNo into OtherVNI.
1691     assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
1692     assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
1693     Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
1694     DEBUG(dbgs() << "\t\tmerge " << PrintReg(LI.reg) << ':' << ValNo << '@'
1695                  << LI.getValNumInfo(ValNo)->def << " into "
1696                  << PrintReg(Other.LI.reg) << ':' << V.OtherVNI->id << '@'
1697                  << V.OtherVNI->def << " --> @"
1698                  << NewVNInfo[Assignments[ValNo]]->def << '\n');
1699     break;
1700   case CR_Replace:
1701   case CR_Unresolved:
1702     // The other value is going to be pruned if this join is successful.
1703     assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
1704     Other.Vals[V.OtherVNI->id].Pruned = true;
1705     // Fall through.
1706   default:
1707     // This value number needs to go in the final joined live range.
1708     Assignments[ValNo] = NewVNInfo.size();
1709     NewVNInfo.push_back(LI.getValNumInfo(ValNo));
1710     break;
1711   }
1712 }
1713
1714 bool JoinVals::mapValues(JoinVals &Other) {
1715   for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1716     computeAssignment(i, Other);
1717     if (Vals[i].Resolution == CR_Impossible) {
1718       DEBUG(dbgs() << "\t\tinterference at " << PrintReg(LI.reg) << ':' << i
1719                    << '@' << LI.getValNumInfo(i)->def << '\n');
1720       return false;
1721     }
1722   }
1723   return true;
1724 }
1725
1726 /// Assuming ValNo is going to clobber some valid lanes in Other.LI, compute
1727 /// the extent of the tainted lanes in the block.
1728 ///
1729 /// Multiple values in Other.LI can be affected since partial redefinitions can
1730 /// preserve previously tainted lanes.
1731 ///
1732 ///   1 %dst = VLOAD           <-- Define all lanes in %dst
1733 ///   2 %src = FOO             <-- ValNo to be joined with %dst:ssub0
1734 ///   3 %dst:ssub1 = BAR       <-- Partial redef doesn't clear taint in ssub0
1735 ///   4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
1736 ///
1737 /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
1738 /// entry to TaintedVals.
1739 ///
1740 /// Returns false if the tainted lanes extend beyond the basic block.
1741 bool JoinVals::
1742 taintExtent(unsigned ValNo, unsigned TaintedLanes, JoinVals &Other,
1743             SmallVectorImpl<std::pair<SlotIndex, unsigned> > &TaintExtent) {
1744   VNInfo *VNI = LI.getValNumInfo(ValNo);
1745   MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1746   SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
1747
1748   // Scan Other.LI from VNI.def to MBBEnd.
1749   LiveInterval::iterator OtherI = Other.LI.find(VNI->def);
1750   assert(OtherI != Other.LI.end() && "No conflict?");
1751   do {
1752     // OtherI is pointing to a tainted value. Abort the join if the tainted
1753     // lanes escape the block.
1754     SlotIndex End = OtherI->end;
1755     if (End >= MBBEnd) {
1756       DEBUG(dbgs() << "\t\ttaints global " << PrintReg(Other.LI.reg) << ':'
1757                    << OtherI->valno->id << '@' << OtherI->start << '\n');
1758       return false;
1759     }
1760     DEBUG(dbgs() << "\t\ttaints local " << PrintReg(Other.LI.reg) << ':'
1761                  << OtherI->valno->id << '@' << OtherI->start
1762                  << " to " << End << '\n');
1763     // A dead def is not a problem.
1764     if (End.isDead())
1765       break;
1766     TaintExtent.push_back(std::make_pair(End, TaintedLanes));
1767
1768     // Check for another def in the MBB.
1769     if (++OtherI == Other.LI.end() || OtherI->start >= MBBEnd)
1770       break;
1771
1772     // Lanes written by the new def are no longer tainted.
1773     const Val &OV = Other.Vals[OtherI->valno->id];
1774     TaintedLanes &= ~OV.WriteLanes;
1775     if (!OV.RedefVNI)
1776       break;
1777   } while (TaintedLanes);
1778   return true;
1779 }
1780
1781 /// Return true if MI uses any of the given Lanes from Reg.
1782 /// This does not include partial redefinitions of Reg.
1783 bool JoinVals::usesLanes(MachineInstr *MI, unsigned Reg, unsigned SubIdx,
1784                          unsigned Lanes) {
1785   if (MI->isDebugValue())
1786     return false;
1787   for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
1788     if (!MO->isReg() || MO->isDef() || MO->getReg() != Reg)
1789       continue;
1790     if (!MO->readsReg())
1791       continue;
1792     if (Lanes & TRI->getSubRegIndexLaneMask(
1793                   TRI->composeSubRegIndices(SubIdx, MO->getSubReg())))
1794       return true;
1795   }
1796   return false;
1797 }
1798
1799 bool JoinVals::resolveConflicts(JoinVals &Other) {
1800   for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1801     Val &V = Vals[i];
1802     assert (V.Resolution != CR_Impossible && "Unresolvable conflict");
1803     if (V.Resolution != CR_Unresolved)
1804       continue;
1805     DEBUG(dbgs() << "\t\tconflict at " << PrintReg(LI.reg) << ':' << i
1806                  << '@' << LI.getValNumInfo(i)->def << '\n');
1807     ++NumLaneConflicts;
1808     assert(V.OtherVNI && "Inconsistent conflict resolution.");
1809     VNInfo *VNI = LI.getValNumInfo(i);
1810     const Val &OtherV = Other.Vals[V.OtherVNI->id];
1811
1812     // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
1813     // join, those lanes will be tainted with a wrong value. Get the extent of
1814     // the tainted lanes.
1815     unsigned TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
1816     SmallVector<std::pair<SlotIndex, unsigned>, 8> TaintExtent;
1817     if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
1818       // Tainted lanes would extend beyond the basic block.
1819       return false;
1820
1821     assert(!TaintExtent.empty() && "There should be at least one conflict.");
1822
1823     // Now look at the instructions from VNI->def to TaintExtent (inclusive).
1824     MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1825     MachineBasicBlock::iterator MI = MBB->begin();
1826     if (!VNI->isPHIDef()) {
1827       MI = Indexes->getInstructionFromIndex(VNI->def);
1828       // No need to check the instruction defining VNI for reads.
1829       ++MI;
1830     }
1831     assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
1832            "Interference ends on VNI->def. Should have been handled earlier");
1833     MachineInstr *LastMI =
1834       Indexes->getInstructionFromIndex(TaintExtent.front().first);
1835     assert(LastMI && "Range must end at a proper instruction");
1836     unsigned TaintNum = 0;
1837     for(;;) {
1838       assert(MI != MBB->end() && "Bad LastMI");
1839       if (usesLanes(MI, Other.LI.reg, Other.SubIdx, TaintedLanes)) {
1840         DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
1841         return false;
1842       }
1843       // LastMI is the last instruction to use the current value.
1844       if (&*MI == LastMI) {
1845         if (++TaintNum == TaintExtent.size())
1846           break;
1847         LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
1848         assert(LastMI && "Range must end at a proper instruction");
1849         TaintedLanes = TaintExtent[TaintNum].second;
1850       }
1851       ++MI;
1852     }
1853
1854     // The tainted lanes are unused.
1855     V.Resolution = CR_Replace;
1856     ++NumLaneResolves;
1857   }
1858   return true;
1859 }
1860
1861 // Determine if ValNo is a copy of a value number in LI or Other.LI that will
1862 // be pruned:
1863 //
1864 //   %dst = COPY %src
1865 //   %src = COPY %dst  <-- This value to be pruned.
1866 //   %dst = COPY %src  <-- This value is a copy of a pruned value.
1867 //
1868 bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
1869   Val &V = Vals[ValNo];
1870   if (V.Pruned || V.PrunedComputed)
1871     return V.Pruned;
1872
1873   if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
1874     return V.Pruned;
1875
1876   // Follow copies up the dominator tree and check if any intermediate value
1877   // has been pruned.
1878   V.PrunedComputed = true;
1879   V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
1880   return V.Pruned;
1881 }
1882
1883 void JoinVals::pruneValues(JoinVals &Other,
1884                            SmallVectorImpl<SlotIndex> &EndPoints) {
1885   for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1886     SlotIndex Def = LI.getValNumInfo(i)->def;
1887     switch (Vals[i].Resolution) {
1888     case CR_Keep:
1889       break;
1890     case CR_Replace: {
1891       // This value takes precedence over the value in Other.LI.
1892       LIS->pruneValue(&Other.LI, Def, &EndPoints);
1893       // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
1894       // instructions are only inserted to provide a live-out value for PHI
1895       // predecessors, so the instruction should simply go away once its value
1896       // has been replaced.
1897       Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
1898       bool EraseImpDef = OtherV.ErasableImplicitDef &&
1899                          OtherV.Resolution == CR_Keep;
1900       if (!Def.isBlock()) {
1901         // Remove <def,read-undef> flags. This def is now a partial redef.
1902         // Also remove <def,dead> flags since the joined live range will
1903         // continue past this instruction.
1904         for (MIOperands MO(Indexes->getInstructionFromIndex(Def));
1905              MO.isValid(); ++MO)
1906           if (MO->isReg() && MO->isDef() && MO->getReg() == LI.reg) {
1907             MO->setIsUndef(EraseImpDef);
1908             MO->setIsDead(false);
1909           }
1910         // This value will reach instructions below, but we need to make sure
1911         // the live range also reaches the instruction at Def.
1912         if (!EraseImpDef)
1913           EndPoints.push_back(Def);
1914       }
1915       DEBUG(dbgs() << "\t\tpruned " << PrintReg(Other.LI.reg) << " at " << Def
1916                    << ": " << Other.LI << '\n');
1917       break;
1918     }
1919     case CR_Erase:
1920     case CR_Merge:
1921       if (isPrunedValue(i, Other)) {
1922         // This value is ultimately a copy of a pruned value in LI or Other.LI.
1923         // We can no longer trust the value mapping computed by
1924         // computeAssignment(), the value that was originally copied could have
1925         // been replaced.
1926         LIS->pruneValue(&LI, Def, &EndPoints);
1927         DEBUG(dbgs() << "\t\tpruned all of " << PrintReg(LI.reg) << " at "
1928                      << Def << ": " << LI << '\n');
1929       }
1930       break;
1931     case CR_Unresolved:
1932     case CR_Impossible:
1933       llvm_unreachable("Unresolved conflicts");
1934     }
1935   }
1936 }
1937
1938 void JoinVals::eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs,
1939                            SmallVectorImpl<unsigned> &ShrinkRegs) {
1940   for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1941     // Get the def location before markUnused() below invalidates it.
1942     SlotIndex Def = LI.getValNumInfo(i)->def;
1943     switch (Vals[i].Resolution) {
1944     case CR_Keep:
1945       // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
1946       // longer. The IMPLICIT_DEF instructions are only inserted by
1947       // PHIElimination to guarantee that all PHI predecessors have a value.
1948       if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned)
1949         break;
1950       // Remove value number i from LI. Note that this VNInfo is still present
1951       // in NewVNInfo, so it will appear as an unused value number in the final
1952       // joined interval.
1953       LI.getValNumInfo(i)->markUnused();
1954       LI.removeValNo(LI.getValNumInfo(i));
1955       DEBUG(dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LI << '\n');
1956       // FALL THROUGH.
1957
1958     case CR_Erase: {
1959       MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
1960       assert(MI && "No instruction to erase");
1961       if (MI->isCopy()) {
1962         unsigned Reg = MI->getOperand(1).getReg();
1963         if (TargetRegisterInfo::isVirtualRegister(Reg) &&
1964             Reg != CP.getSrcReg() && Reg != CP.getDstReg())
1965           ShrinkRegs.push_back(Reg);
1966       }
1967       ErasedInstrs.insert(MI);
1968       DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
1969       LIS->RemoveMachineInstrFromMaps(MI);
1970       MI->eraseFromParent();
1971       break;
1972     }
1973     default:
1974       break;
1975     }
1976   }
1977 }
1978
1979 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
1980   SmallVector<VNInfo*, 16> NewVNInfo;
1981   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1982   LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
1983   JoinVals RHSVals(RHS, CP.getSrcIdx(), NewVNInfo, CP, LIS, TRI);
1984   JoinVals LHSVals(LHS, CP.getDstIdx(), NewVNInfo, CP, LIS, TRI);
1985
1986   DEBUG(dbgs() << "\t\tRHS = " << RHS
1987                << "\n\t\tLHS = " << LHS
1988                << '\n');
1989
1990   // First compute NewVNInfo and the simple value mappings.
1991   // Detect impossible conflicts early.
1992   if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
1993     return false;
1994
1995   // Some conflicts can only be resolved after all values have been mapped.
1996   if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
1997     return false;
1998
1999   // All clear, the live ranges can be merged.
2000
2001   // The merging algorithm in LiveInterval::join() can't handle conflicting
2002   // value mappings, so we need to remove any live ranges that overlap a
2003   // CR_Replace resolution. Collect a set of end points that can be used to
2004   // restore the live range after joining.
2005   SmallVector<SlotIndex, 8> EndPoints;
2006   LHSVals.pruneValues(RHSVals, EndPoints);
2007   RHSVals.pruneValues(LHSVals, EndPoints);
2008
2009   // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
2010   // registers to require trimming.
2011   SmallVector<unsigned, 8> ShrinkRegs;
2012   LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
2013   RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
2014   while (!ShrinkRegs.empty())
2015     LIS->shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
2016
2017   // Join RHS into LHS.
2018   LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo);
2019
2020   // Kill flags are going to be wrong if the live ranges were overlapping.
2021   // Eventually, we should simply clear all kill flags when computing live
2022   // ranges. They are reinserted after register allocation.
2023   MRI->clearKillFlags(LHS.reg);
2024   MRI->clearKillFlags(RHS.reg);
2025
2026   if (EndPoints.empty())
2027     return true;
2028
2029   // Recompute the parts of the live range we had to remove because of
2030   // CR_Replace conflicts.
2031   DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
2032                << " points: " << LHS << '\n');
2033   LIS->extendToIndices(LHS, EndPoints);
2034   return true;
2035 }
2036
2037 /// joinIntervals - Attempt to join these two intervals.  On failure, this
2038 /// returns false.
2039 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
2040   return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
2041 }
2042
2043 namespace {
2044 // Information concerning MBB coalescing priority.
2045 struct MBBPriorityInfo {
2046   MachineBasicBlock *MBB;
2047   unsigned Depth;
2048   bool IsSplit;
2049
2050   MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
2051     : MBB(mbb), Depth(depth), IsSplit(issplit) {}
2052 };
2053 }
2054
2055 // C-style comparator that sorts first based on the loop depth of the basic
2056 // block (the unsigned), and then on the MBB number.
2057 //
2058 // EnableGlobalCopies assumes that the primary sort key is loop depth.
2059 static int compareMBBPriority(const MBBPriorityInfo *LHS,
2060                               const MBBPriorityInfo *RHS) {
2061   // Deeper loops first
2062   if (LHS->Depth != RHS->Depth)
2063     return LHS->Depth > RHS->Depth ? -1 : 1;
2064
2065   // Try to unsplit critical edges next.
2066   if (LHS->IsSplit != RHS->IsSplit)
2067     return LHS->IsSplit ? -1 : 1;
2068
2069   // Prefer blocks that are more connected in the CFG. This takes care of
2070   // the most difficult copies first while intervals are short.
2071   unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size();
2072   unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size();
2073   if (cl != cr)
2074     return cl > cr ? -1 : 1;
2075
2076   // As a last resort, sort by block number.
2077   return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1;
2078 }
2079
2080 /// \returns true if the given copy uses or defines a local live range.
2081 static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) {
2082   if (!Copy->isCopy())
2083     return false;
2084
2085   if (Copy->getOperand(1).isUndef())
2086     return false;
2087
2088   unsigned SrcReg = Copy->getOperand(1).getReg();
2089   unsigned DstReg = Copy->getOperand(0).getReg();
2090   if (TargetRegisterInfo::isPhysicalRegister(SrcReg)
2091       || TargetRegisterInfo::isPhysicalRegister(DstReg))
2092     return false;
2093
2094   return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg))
2095     || LIS->intervalIsInOneMBB(LIS->getInterval(DstReg));
2096 }
2097
2098 // Try joining WorkList copies starting from index From.
2099 // Null out any successful joins.
2100 bool RegisterCoalescer::
2101 copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) {
2102   bool Progress = false;
2103   for (unsigned i = 0, e = CurrList.size(); i != e; ++i) {
2104     if (!CurrList[i])
2105       continue;
2106     // Skip instruction pointers that have already been erased, for example by
2107     // dead code elimination.
2108     if (ErasedInstrs.erase(CurrList[i])) {
2109       CurrList[i] = 0;
2110       continue;
2111     }
2112     bool Again = false;
2113     bool Success = joinCopy(CurrList[i], Again);
2114     Progress |= Success;
2115     if (Success || !Again)
2116       CurrList[i] = 0;
2117   }
2118   return Progress;
2119 }
2120
2121 void
2122 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
2123   DEBUG(dbgs() << MBB->getName() << ":\n");
2124
2125   // Collect all copy-like instructions in MBB. Don't start coalescing anything
2126   // yet, it might invalidate the iterator.
2127   const unsigned PrevSize = WorkList.size();
2128   if (JoinGlobalCopies) {
2129     // Coalesce copies bottom-up to coalesce local defs before local uses. They
2130     // are not inherently easier to resolve, but slightly preferable until we
2131     // have local live range splitting. In particular this is required by
2132     // cmp+jmp macro fusion.
2133     for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2134          MII != E; ++MII) {
2135       if (!MII->isCopyLike())
2136         continue;
2137       if (isLocalCopy(&(*MII), LIS))
2138         LocalWorkList.push_back(&(*MII));
2139       else
2140         WorkList.push_back(&(*MII));
2141     }
2142   }
2143   else {
2144      for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2145           MII != E; ++MII)
2146        if (MII->isCopyLike())
2147          WorkList.push_back(MII);
2148   }
2149   // Try coalescing the collected copies immediately, and remove the nulls.
2150   // This prevents the WorkList from getting too large since most copies are
2151   // joinable on the first attempt.
2152   MutableArrayRef<MachineInstr*>
2153     CurrList(WorkList.begin() + PrevSize, WorkList.end());
2154   if (copyCoalesceWorkList(CurrList))
2155     WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
2156                                (MachineInstr*)0), WorkList.end());
2157 }
2158
2159 void RegisterCoalescer::coalesceLocals() {
2160   copyCoalesceWorkList(LocalWorkList);
2161   for (unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) {
2162     if (LocalWorkList[j])
2163       WorkList.push_back(LocalWorkList[j]);
2164   }
2165   LocalWorkList.clear();
2166 }
2167
2168 void RegisterCoalescer::joinAllIntervals() {
2169   DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
2170   assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around.");
2171
2172   std::vector<MBBPriorityInfo> MBBs;
2173   MBBs.reserve(MF->size());
2174   for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
2175     MachineBasicBlock *MBB = I;
2176     MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB),
2177                                    JoinSplitEdges && isSplitEdge(MBB)));
2178   }
2179   array_pod_sort(MBBs.begin(), MBBs.end(), compareMBBPriority);
2180
2181   // Coalesce intervals in MBB priority order.
2182   unsigned CurrDepth = UINT_MAX;
2183   for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
2184     // Try coalescing the collected local copies for deeper loops.
2185     if (JoinGlobalCopies && MBBs[i].Depth < CurrDepth) {
2186       coalesceLocals();
2187       CurrDepth = MBBs[i].Depth;
2188     }
2189     copyCoalesceInMBB(MBBs[i].MBB);
2190   }
2191   coalesceLocals();
2192
2193   // Joining intervals can allow other intervals to be joined.  Iteratively join
2194   // until we make no progress.
2195   while (copyCoalesceWorkList(WorkList))
2196     /* empty */ ;
2197 }
2198
2199 void RegisterCoalescer::releaseMemory() {
2200   ErasedInstrs.clear();
2201   WorkList.clear();
2202   DeadDefs.clear();
2203   InflateRegs.clear();
2204 }
2205
2206 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
2207   MF = &fn;
2208   MRI = &fn.getRegInfo();
2209   TM = &fn.getTarget();
2210   TRI = TM->getRegisterInfo();
2211   TII = TM->getInstrInfo();
2212   LIS = &getAnalysis<LiveIntervals>();
2213   AA = &getAnalysis<AliasAnalysis>();
2214   Loops = &getAnalysis<MachineLoopInfo>();
2215
2216   const TargetSubtargetInfo &ST = TM->getSubtarget<TargetSubtargetInfo>();
2217   if (EnableGlobalCopies == cl::BOU_UNSET)
2218     JoinGlobalCopies = ST.useMachineScheduler();
2219   else
2220     JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE);
2221
2222   // The MachineScheduler does not currently require JoinSplitEdges. This will
2223   // either be enabled unconditionally or replaced by a more general live range
2224   // splitting optimization.
2225   JoinSplitEdges = EnableJoinSplits;
2226
2227   DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
2228                << "********** Function: " << MF->getName() << '\n');
2229
2230   if (VerifyCoalescing)
2231     MF->verify(this, "Before register coalescing");
2232
2233   RegClassInfo.runOnMachineFunction(fn);
2234
2235   // Join (coalesce) intervals if requested.
2236   if (EnableJoining)
2237     joinAllIntervals();
2238
2239   // After deleting a lot of copies, register classes may be less constrained.
2240   // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
2241   // DPR inflation.
2242   array_pod_sort(InflateRegs.begin(), InflateRegs.end());
2243   InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
2244                     InflateRegs.end());
2245   DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
2246   for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
2247     unsigned Reg = InflateRegs[i];
2248     if (MRI->reg_nodbg_empty(Reg))
2249       continue;
2250     if (MRI->recomputeRegClass(Reg, *TM)) {
2251       DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
2252                    << MRI->getRegClass(Reg)->getName() << '\n');
2253       ++NumInflated;
2254     }
2255   }
2256
2257   DEBUG(dump());
2258   if (VerifyCoalescing)
2259     MF->verify(this, "After register coalescing");
2260   return true;
2261 }
2262
2263 /// print - Implement the dump method.
2264 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {
2265    LIS->print(O, m);
2266 }