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