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