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