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