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