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