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