Add print methods
[oota-llvm.git] / lib / CodeGen / SplitKit.cpp
1 //===---------- SplitKit.cpp - Toolkit for splitting live ranges ----------===//
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 contains the SplitAnalysis class as well as mutator functions for
11 // live range splitting.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "splitter"
16 #include "SplitKit.h"
17 #include "LiveRangeEdit.h"
18 #include "VirtRegMap.h"
19 #include "llvm/CodeGen/CalcSpillWeights.h"
20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29
30 using namespace llvm;
31
32 static cl::opt<bool>
33 AllowSplit("spiller-splits-edges",
34            cl::desc("Allow critical edge splitting during spilling"));
35
36 //===----------------------------------------------------------------------===//
37 //                                 Split Analysis
38 //===----------------------------------------------------------------------===//
39
40 SplitAnalysis::SplitAnalysis(const MachineFunction &mf,
41                              const LiveIntervals &lis,
42                              const MachineLoopInfo &mli)
43   : mf_(mf),
44     lis_(lis),
45     loops_(mli),
46     tii_(*mf.getTarget().getInstrInfo()),
47     curli_(0) {}
48
49 void SplitAnalysis::clear() {
50   usingInstrs_.clear();
51   usingBlocks_.clear();
52   usingLoops_.clear();
53   curli_ = 0;
54 }
55
56 bool SplitAnalysis::canAnalyzeBranch(const MachineBasicBlock *MBB) {
57   MachineBasicBlock *T, *F;
58   SmallVector<MachineOperand, 4> Cond;
59   return !tii_.AnalyzeBranch(const_cast<MachineBasicBlock&>(*MBB), T, F, Cond);
60 }
61
62 /// analyzeUses - Count instructions, basic blocks, and loops using curli.
63 void SplitAnalysis::analyzeUses() {
64   const MachineRegisterInfo &MRI = mf_.getRegInfo();
65   for (MachineRegisterInfo::reg_iterator I = MRI.reg_begin(curli_->reg);
66        MachineInstr *MI = I.skipInstruction();) {
67     if (MI->isDebugValue() || !usingInstrs_.insert(MI))
68       continue;
69     MachineBasicBlock *MBB = MI->getParent();
70     if (usingBlocks_[MBB]++)
71       continue;
72     for (MachineLoop *Loop = loops_.getLoopFor(MBB); Loop;
73          Loop = Loop->getParentLoop())
74       usingLoops_[Loop]++;
75   }
76   DEBUG(dbgs() << "  counted "
77                << usingInstrs_.size() << " instrs, "
78                << usingBlocks_.size() << " blocks, "
79                << usingLoops_.size()  << " loops.\n");
80 }
81
82 void SplitAnalysis::print(const BlockPtrSet &B, raw_ostream &OS) const {
83   for (BlockPtrSet::const_iterator I = B.begin(), E = B.end(); I != E; ++I) {
84     unsigned count = usingBlocks_.lookup(*I);
85     OS << " BB#" << (*I)->getNumber();
86     if (count)
87       OS << '(' << count << ')';
88   }
89 }
90
91 // Get three sets of basic blocks surrounding a loop: Blocks inside the loop,
92 // predecessor blocks, and exit blocks.
93 void SplitAnalysis::getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks) {
94   Blocks.clear();
95
96   // Blocks in the loop.
97   Blocks.Loop.insert(Loop->block_begin(), Loop->block_end());
98
99   // Predecessor blocks.
100   const MachineBasicBlock *Header = Loop->getHeader();
101   for (MachineBasicBlock::const_pred_iterator I = Header->pred_begin(),
102        E = Header->pred_end(); I != E; ++I)
103     if (!Blocks.Loop.count(*I))
104       Blocks.Preds.insert(*I);
105
106   // Exit blocks.
107   for (MachineLoop::block_iterator I = Loop->block_begin(),
108        E = Loop->block_end(); I != E; ++I) {
109     const MachineBasicBlock *MBB = *I;
110     for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
111        SE = MBB->succ_end(); SI != SE; ++SI)
112       if (!Blocks.Loop.count(*SI))
113         Blocks.Exits.insert(*SI);
114   }
115 }
116
117 void SplitAnalysis::print(const LoopBlocks &B, raw_ostream &OS) const {
118   OS << "Loop:";
119   print(B.Loop, OS);
120   OS << ", preds:";
121   print(B.Preds, OS);
122   OS << ", exits:";
123   print(B.Exits, OS);
124 }
125
126 /// analyzeLoopPeripheralUse - Return an enum describing how curli_ is used in
127 /// and around the Loop.
128 SplitAnalysis::LoopPeripheralUse SplitAnalysis::
129 analyzeLoopPeripheralUse(const SplitAnalysis::LoopBlocks &Blocks) {
130   LoopPeripheralUse use = ContainedInLoop;
131   for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
132        I != E; ++I) {
133     const MachineBasicBlock *MBB = I->first;
134     // Is this a peripheral block?
135     if (use < MultiPeripheral &&
136         (Blocks.Preds.count(MBB) || Blocks.Exits.count(MBB))) {
137       if (I->second > 1) use = MultiPeripheral;
138       else               use = SinglePeripheral;
139       continue;
140     }
141     // Is it a loop block?
142     if (Blocks.Loop.count(MBB))
143       continue;
144     // It must be an unrelated block.
145     DEBUG(dbgs() << ", outside: BB#" << MBB->getNumber());
146     return OutsideLoop;
147   }
148   return use;
149 }
150
151 /// getCriticalExits - It may be necessary to partially break critical edges
152 /// leaving the loop if an exit block has phi uses of curli. Collect the exit
153 /// blocks that need special treatment into CriticalExits.
154 void SplitAnalysis::getCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
155                                      BlockPtrSet &CriticalExits) {
156   CriticalExits.clear();
157
158   // A critical exit block contains a phi def of curli, and has a predecessor
159   // that is not in the loop nor a loop predecessor.
160   // For such an exit block, the edges carrying the new variable must be moved
161   // to a new pre-exit block.
162   for (BlockPtrSet::iterator I = Blocks.Exits.begin(), E = Blocks.Exits.end();
163        I != E; ++I) {
164     const MachineBasicBlock *Succ = *I;
165     SlotIndex SuccIdx = lis_.getMBBStartIdx(Succ);
166     VNInfo *SuccVNI = curli_->getVNInfoAt(SuccIdx);
167     // This exit may not have curli live in at all. No need to split.
168     if (!SuccVNI)
169       continue;
170     // If this is not a PHI def, it is either using a value from before the
171     // loop, or a value defined inside the loop. Both are safe.
172     if (!SuccVNI->isPHIDef() || SuccVNI->def.getBaseIndex() != SuccIdx)
173       continue;
174     // This exit block does have a PHI. Does it also have a predecessor that is
175     // not a loop block or loop predecessor?
176     for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
177          PE = Succ->pred_end(); PI != PE; ++PI) {
178       const MachineBasicBlock *Pred = *PI;
179       if (Blocks.Loop.count(Pred) || Blocks.Preds.count(Pred))
180         continue;
181       // This is a critical exit block, and we need to split the exit edge.
182       CriticalExits.insert(Succ);
183       break;
184     }
185   }
186 }
187
188 /// canSplitCriticalExits - Return true if it is possible to insert new exit
189 /// blocks before the blocks in CriticalExits.
190 bool
191 SplitAnalysis::canSplitCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
192                                      BlockPtrSet &CriticalExits) {
193   // If we don't allow critical edge splitting, require no critical exits.
194   if (!AllowSplit)
195     return CriticalExits.empty();
196
197   for (BlockPtrSet::iterator I = CriticalExits.begin(), E = CriticalExits.end();
198        I != E; ++I) {
199     const MachineBasicBlock *Succ = *I;
200     // We want to insert a new pre-exit MBB before Succ, and change all the
201     // in-loop blocks to branch to the pre-exit instead of Succ.
202     // Check that all the in-loop predecessors can be changed.
203     for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
204          PE = Succ->pred_end(); PI != PE; ++PI) {
205       const MachineBasicBlock *Pred = *PI;
206       // The external predecessors won't be altered.
207       if (!Blocks.Loop.count(Pred) && !Blocks.Preds.count(Pred))
208         continue;
209       if (!canAnalyzeBranch(Pred))
210         return false;
211     }
212
213     // If Succ's layout predecessor falls through, that too must be analyzable.
214     // We need to insert the pre-exit block in the gap.
215     MachineFunction::const_iterator MFI = Succ;
216     if (MFI == mf_.begin())
217       continue;
218     if (!canAnalyzeBranch(--MFI))
219       return false;
220   }
221   // No problems found.
222   return true;
223 }
224
225 void SplitAnalysis::analyze(const LiveInterval *li) {
226   clear();
227   curli_ = li;
228   analyzeUses();
229 }
230
231 const MachineLoop *SplitAnalysis::getBestSplitLoop() {
232   assert(curli_ && "Call analyze() before getBestSplitLoop");
233   if (usingLoops_.empty())
234     return 0;
235
236   LoopPtrSet Loops;
237   LoopBlocks Blocks;
238   BlockPtrSet CriticalExits;
239
240   // We split around loops where curli is used outside the periphery.
241   for (LoopCountMap::const_iterator I = usingLoops_.begin(),
242        E = usingLoops_.end(); I != E; ++I) {
243     const MachineLoop *Loop = I->first;
244     getLoopBlocks(Loop, Blocks);
245     DEBUG({ dbgs() << "  "; print(Blocks, dbgs()); });
246
247     switch(analyzeLoopPeripheralUse(Blocks)) {
248     case OutsideLoop:
249       break;
250     case MultiPeripheral:
251       // FIXME: We could split a live range with multiple uses in a peripheral
252       // block and still make progress. However, it is possible that splitting
253       // another live range will insert copies into a peripheral block, and
254       // there is a small chance we can enter an infinity loop, inserting copies
255       // forever.
256       // For safety, stick to splitting live ranges with uses outside the
257       // periphery.
258       DEBUG(dbgs() << ": multiple peripheral uses\n");
259       break;
260     case ContainedInLoop:
261       DEBUG(dbgs() << ": fully contained\n");
262       continue;
263     case SinglePeripheral:
264       DEBUG(dbgs() << ": single peripheral use\n");
265       continue;
266     }
267     // Will it be possible to split around this loop?
268     getCriticalExits(Blocks, CriticalExits);
269     DEBUG(dbgs() << ": " << CriticalExits.size() << " critical exits\n");
270     if (!canSplitCriticalExits(Blocks, CriticalExits))
271       continue;
272     // This is a possible split.
273     Loops.insert(Loop);
274   }
275
276   DEBUG(dbgs() << "  getBestSplitLoop found " << Loops.size()
277                << " candidate loops.\n");
278
279   if (Loops.empty())
280     return 0;
281
282   // Pick the earliest loop.
283   // FIXME: Are there other heuristics to consider?
284   const MachineLoop *Best = 0;
285   SlotIndex BestIdx;
286   for (LoopPtrSet::const_iterator I = Loops.begin(), E = Loops.end(); I != E;
287        ++I) {
288     SlotIndex Idx = lis_.getMBBStartIdx((*I)->getHeader());
289     if (!Best || Idx < BestIdx)
290       Best = *I, BestIdx = Idx;
291   }
292   DEBUG(dbgs() << "  getBestSplitLoop found " << *Best);
293   return Best;
294 }
295
296 /// getMultiUseBlocks - if curli has more than one use in a basic block, it
297 /// may be an advantage to split curli for the duration of the block.
298 bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
299   // If curli is local to one block, there is no point to splitting it.
300   if (usingBlocks_.size() <= 1)
301     return false;
302   // Add blocks with multiple uses.
303   for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
304        I != E; ++I)
305     switch (I->second) {
306     case 0:
307     case 1:
308       continue;
309     case 2: {
310       // It doesn't pay to split a 2-instr block if it redefines curli.
311       VNInfo *VN1 = curli_->getVNInfoAt(lis_.getMBBStartIdx(I->first));
312       VNInfo *VN2 =
313         curli_->getVNInfoAt(lis_.getMBBEndIdx(I->first).getPrevIndex());
314       // live-in and live-out with a different value.
315       if (VN1 && VN2 && VN1 != VN2)
316         continue;
317     } // Fall through.
318     default:
319       Blocks.insert(I->first);
320     }
321   return !Blocks.empty();
322 }
323
324 //===----------------------------------------------------------------------===//
325 //                               LiveIntervalMap
326 //===----------------------------------------------------------------------===//
327
328 // Work around the fact that the std::pair constructors are broken for pointer
329 // pairs in some implementations. makeVV(x, 0) works.
330 static inline std::pair<const VNInfo*, VNInfo*>
331 makeVV(const VNInfo *a, VNInfo *b) {
332   return std::make_pair(a, b);
333 }
334
335 void LiveIntervalMap::reset(LiveInterval *li) {
336   li_ = li;
337   valueMap_.clear();
338 }
339
340 bool LiveIntervalMap::isComplexMapped(const VNInfo *ParentVNI) const {
341   ValueMap::const_iterator i = valueMap_.find(ParentVNI);
342   return i != valueMap_.end() && i->second == 0;
343 }
344
345 // defValue - Introduce a li_ def for ParentVNI that could be later than
346 // ParentVNI->def.
347 VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) {
348   assert(li_ && "call reset first");
349   assert(ParentVNI && "Mapping  NULL value");
350   assert(Idx.isValid() && "Invalid SlotIndex");
351   assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
352
353   // Create a new value.
354   VNInfo *VNI = li_->getNextValue(Idx, 0, lis_.getVNInfoAllocator());
355
356   // Use insert for lookup, so we can add missing values with a second lookup.
357   std::pair<ValueMap::iterator,bool> InsP =
358     valueMap_.insert(makeVV(ParentVNI, Idx == ParentVNI->def ? VNI : 0));
359
360   // This is now a complex def. Mark with a NULL in valueMap.
361   if (!InsP.second)
362     InsP.first->second = 0;
363
364   return VNI;
365 }
366
367
368 // mapValue - Find the mapped value for ParentVNI at Idx.
369 // Potentially create phi-def values.
370 VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx,
371                                   bool *simple) {
372   assert(li_ && "call reset first");
373   assert(ParentVNI && "Mapping  NULL value");
374   assert(Idx.isValid() && "Invalid SlotIndex");
375   assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
376
377   // Use insert for lookup, so we can add missing values with a second lookup.
378   std::pair<ValueMap::iterator,bool> InsP =
379     valueMap_.insert(makeVV(ParentVNI, 0));
380
381   // This was an unknown value. Create a simple mapping.
382   if (InsP.second) {
383     if (simple) *simple = true;
384     return InsP.first->second = li_->createValueCopy(ParentVNI,
385                                                      lis_.getVNInfoAllocator());
386   }
387
388   // This was a simple mapped value.
389   if (InsP.first->second) {
390     if (simple) *simple = true;
391     return InsP.first->second;
392   }
393
394   // This is a complex mapped value. There may be multiple defs, and we may need
395   // to create phi-defs.
396   if (simple) *simple = false;
397   MachineBasicBlock *IdxMBB = lis_.getMBBFromIndex(Idx);
398   assert(IdxMBB && "No MBB at Idx");
399
400   // Is there a def in the same MBB we can extend?
401   if (VNInfo *VNI = extendTo(IdxMBB, Idx))
402     return VNI;
403
404   // Now for the fun part. We know that ParentVNI potentially has multiple defs,
405   // and we may need to create even more phi-defs to preserve VNInfo SSA form.
406   // Perform a depth-first search for predecessor blocks where we know the
407   // dominating VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
408
409   // Track MBBs where we have created or learned the dominating value.
410   // This may change during the DFS as we create new phi-defs.
411   typedef DenseMap<MachineBasicBlock*, VNInfo*> MBBValueMap;
412   MBBValueMap DomValue;
413   typedef SplitAnalysis::BlockPtrSet BlockPtrSet;
414   BlockPtrSet Visited;
415
416   // Iterate over IdxMBB predecessors in a depth-first order.
417   // Skip begin() since that is always IdxMBB.
418   for (idf_ext_iterator<MachineBasicBlock*, BlockPtrSet>
419          IDFI = llvm::next(idf_ext_begin(IdxMBB, Visited)),
420          IDFE = idf_ext_end(IdxMBB, Visited); IDFI != IDFE;) {
421     MachineBasicBlock *MBB = *IDFI;
422     SlotIndex End = lis_.getMBBEndIdx(MBB).getPrevSlot();
423
424     // We are operating on the restricted CFG where ParentVNI is live.
425     if (parentli_.getVNInfoAt(End) != ParentVNI) {
426       IDFI.skipChildren();
427       continue;
428     }
429
430     // Do we have a dominating value in this block?
431     VNInfo *VNI = extendTo(MBB, End);
432     if (!VNI) {
433       ++IDFI;
434       continue;
435     }
436
437     // Yes, VNI dominates MBB. Make sure we visit MBB again from other paths.
438     Visited.erase(MBB);
439
440     // Track the path back to IdxMBB, creating phi-defs
441     // as needed along the way.
442     for (unsigned PI = IDFI.getPathLength()-1; PI != 0; --PI) {
443       // Start from MBB's immediate successor. End at IdxMBB.
444       MachineBasicBlock *Succ = IDFI.getPath(PI-1);
445       std::pair<MBBValueMap::iterator, bool> InsP =
446         DomValue.insert(MBBValueMap::value_type(Succ, VNI));
447
448       // This is the first time we backtrack to Succ.
449       if (InsP.second)
450         continue;
451
452       // We reached Succ again with the same VNI. Nothing is going to change.
453       VNInfo *OVNI = InsP.first->second;
454       if (OVNI == VNI)
455         break;
456
457       // Succ already has a phi-def. No need to continue.
458       SlotIndex Start = lis_.getMBBStartIdx(Succ);
459       if (OVNI->def == Start)
460         break;
461
462       // We have a collision between the old and new VNI at Succ. That means
463       // neither dominates and we need a new phi-def.
464       VNI = li_->getNextValue(Start, 0, lis_.getVNInfoAllocator());
465       VNI->setIsPHIDef(true);
466       InsP.first->second = VNI;
467
468       // Replace OVNI with VNI in the remaining path.
469       for (; PI > 1 ; --PI) {
470         MBBValueMap::iterator I = DomValue.find(IDFI.getPath(PI-2));
471         if (I == DomValue.end() || I->second != OVNI)
472           break;
473         I->second = VNI;
474       }
475     }
476
477     // No need to search the children, we found a dominating value.
478     IDFI.skipChildren();
479   }
480
481   // The search should at least find a dominating value for IdxMBB.
482   assert(!DomValue.empty() && "Couldn't find a reaching definition");
483
484   // Since we went through the trouble of a full DFS visiting all reaching defs,
485   // the values in DomValue are now accurate. No more phi-defs are needed for
486   // these blocks, so we can color the live ranges.
487   // This makes the next mapValue call much faster.
488   VNInfo *IdxVNI = 0;
489   for (MBBValueMap::iterator I = DomValue.begin(), E = DomValue.end(); I != E;
490        ++I) {
491      MachineBasicBlock *MBB = I->first;
492      VNInfo *VNI = I->second;
493      SlotIndex Start = lis_.getMBBStartIdx(MBB);
494      if (MBB == IdxMBB) {
495        // Don't add full liveness to IdxMBB, stop at Idx.
496        if (Start != Idx)
497          li_->addRange(LiveRange(Start, Idx.getNextSlot(), VNI));
498        // The caller had better add some liveness to IdxVNI, or it leaks.
499        IdxVNI = VNI;
500      } else
501       li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
502   }
503
504   assert(IdxVNI && "Didn't find value for Idx");
505   return IdxVNI;
506 }
507
508 // extendTo - Find the last li_ value defined in MBB at or before Idx. The
509 // parentli_ is assumed to be live at Idx. Extend the live range to Idx.
510 // Return the found VNInfo, or NULL.
511 VNInfo *LiveIntervalMap::extendTo(MachineBasicBlock *MBB, SlotIndex Idx) {
512   assert(li_ && "call reset first");
513   LiveInterval::iterator I = std::upper_bound(li_->begin(), li_->end(), Idx);
514   if (I == li_->begin())
515     return 0;
516   --I;
517   if (I->end <= lis_.getMBBStartIdx(MBB))
518     return 0;
519   if (I->end <= Idx)
520     I->end = Idx.getNextSlot();
521   return I->valno;
522 }
523
524 // addSimpleRange - Add a simple range from parentli_ to li_.
525 // ParentVNI must be live in the [Start;End) interval.
526 void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End,
527                                      const VNInfo *ParentVNI) {
528   assert(li_ && "call reset first");
529   bool simple;
530   VNInfo *VNI = mapValue(ParentVNI, Start, &simple);
531   // A simple mapping is easy.
532   if (simple) {
533     li_->addRange(LiveRange(Start, End, VNI));
534     return;
535   }
536
537   // ParentVNI is a complex value. We must map per MBB.
538   MachineFunction::iterator MBB = lis_.getMBBFromIndex(Start);
539   MachineFunction::iterator MBBE = lis_.getMBBFromIndex(End.getPrevSlot());
540
541   if (MBB == MBBE) {
542     li_->addRange(LiveRange(Start, End, VNI));
543     return;
544   }
545
546   // First block.
547   li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
548
549   // Run sequence of full blocks.
550   for (++MBB; MBB != MBBE; ++MBB) {
551     Start = lis_.getMBBStartIdx(MBB);
552     li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB),
553                             mapValue(ParentVNI, Start)));
554   }
555
556   // Final block.
557   Start = lis_.getMBBStartIdx(MBB);
558   if (Start != End)
559     li_->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start)));
560 }
561
562 /// addRange - Add live ranges to li_ where [Start;End) intersects parentli_.
563 /// All needed values whose def is not inside [Start;End) must be defined
564 /// beforehand so mapValue will work.
565 void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) {
566   assert(li_ && "call reset first");
567   LiveInterval::const_iterator B = parentli_.begin(), E = parentli_.end();
568   LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
569
570   // Check if --I begins before Start and overlaps.
571   if (I != B) {
572     --I;
573     if (I->end > Start)
574       addSimpleRange(Start, std::min(End, I->end), I->valno);
575     ++I;
576   }
577
578   // The remaining ranges begin after Start.
579   for (;I != E && I->start < End; ++I)
580     addSimpleRange(I->start, std::min(End, I->end), I->valno);
581 }
582
583 VNInfo *LiveIntervalMap::defByCopyFrom(unsigned Reg,
584                                        const VNInfo *ParentVNI,
585                                        MachineBasicBlock &MBB,
586                                        MachineBasicBlock::iterator I) {
587   const TargetInstrDesc &TID = MBB.getParent()->getTarget().getInstrInfo()->
588     get(TargetOpcode::COPY);
589   MachineInstr *MI = BuildMI(MBB, I, DebugLoc(), TID, li_->reg).addReg(Reg);
590   SlotIndex DefIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
591   VNInfo *VNI = defValue(ParentVNI, DefIdx);
592   VNI->setCopy(MI);
593   li_->addRange(LiveRange(DefIdx, DefIdx.getNextSlot(), VNI));
594   return VNI;
595 }
596
597 //===----------------------------------------------------------------------===//
598 //                               Split Editor
599 //===----------------------------------------------------------------------===//
600
601 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
602 SplitEditor::SplitEditor(SplitAnalysis &sa, LiveIntervals &lis, VirtRegMap &vrm,
603                          LiveRangeEdit &edit)
604   : sa_(sa), lis_(lis), vrm_(vrm),
605     mri_(vrm.getMachineFunction().getRegInfo()),
606     tii_(*vrm.getMachineFunction().getTarget().getInstrInfo()),
607     edit_(edit),
608     dupli_(lis_, edit.getParent()),
609     openli_(lis_, edit.getParent())
610 {
611 }
612
613 bool SplitEditor::intervalsLiveAt(SlotIndex Idx) const {
614   for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I)
615     if (*I != dupli_.getLI() && (*I)->liveAt(Idx))
616       return true;
617   return false;
618 }
619
620 /// Create a new virtual register and live interval.
621 void SplitEditor::openIntv() {
622   assert(!openli_.getLI() && "Previous LI not closed before openIntv");
623
624   if (!dupli_.getLI())
625     dupli_.reset(&edit_.create(mri_, lis_, vrm_));
626
627   openli_.reset(&edit_.create(mri_, lis_, vrm_));
628 }
629
630 /// enterIntvBefore - Enter openli before the instruction at Idx. If curli is
631 /// not live before Idx, a COPY is not inserted.
632 void SplitEditor::enterIntvBefore(SlotIndex Idx) {
633   assert(openli_.getLI() && "openIntv not called before enterIntvBefore");
634   DEBUG(dbgs() << "    enterIntvBefore " << Idx);
635   VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx.getUseIndex());
636   if (!ParentVNI) {
637     DEBUG(dbgs() << ": not live\n");
638     return;
639   }
640   DEBUG(dbgs() << ": valno " << ParentVNI->id);
641   truncatedValues.insert(ParentVNI);
642   MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
643   assert(MI && "enterIntvBefore called with invalid index");
644   VNInfo *VNI = openli_.defByCopyFrom(edit_.getReg(), ParentVNI,
645                                       *MI->getParent(), MI);
646   openli_.getLI()->addRange(LiveRange(VNI->def, Idx.getDefIndex(), VNI));
647   DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
648 }
649
650 /// enterIntvAtEnd - Enter openli at the end of MBB.
651 void SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
652   assert(openli_.getLI() && "openIntv not called before enterIntvAtEnd");
653   SlotIndex End = lis_.getMBBEndIdx(&MBB);
654   DEBUG(dbgs() << "    enterIntvAtEnd BB#" << MBB.getNumber() << ", " << End);
655   VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(End.getPrevSlot());
656   if (!ParentVNI) {
657     DEBUG(dbgs() << ": not live\n");
658     return;
659   }
660   DEBUG(dbgs() << ": valno " << ParentVNI->id);
661   truncatedValues.insert(ParentVNI);
662   VNInfo *VNI = openli_.defByCopyFrom(edit_.getReg(), ParentVNI,
663                                       MBB, MBB.getFirstTerminator());
664   // Make sure openli is live out of MBB.
665   openli_.getLI()->addRange(LiveRange(VNI->def, End, VNI));
666   DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
667 }
668
669 /// useIntv - indicate that all instructions in MBB should use openli.
670 void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
671   useIntv(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB));
672 }
673
674 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
675   assert(openli_.getLI() && "openIntv not called before useIntv");
676   openli_.addRange(Start, End);
677   DEBUG(dbgs() << "    use [" << Start << ';' << End << "): "
678                << *openli_.getLI() << '\n');
679 }
680
681 /// leaveIntvAfter - Leave openli after the instruction at Idx.
682 void SplitEditor::leaveIntvAfter(SlotIndex Idx) {
683   assert(openli_.getLI() && "openIntv not called before leaveIntvAfter");
684   DEBUG(dbgs() << "    leaveIntvAfter " << Idx);
685
686   // The interval must be live beyond the instruction at Idx.
687   VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx.getBoundaryIndex());
688   if (!ParentVNI) {
689     DEBUG(dbgs() << ": not live\n");
690     return;
691   }
692   DEBUG(dbgs() << ": valno " << ParentVNI->id);
693
694   MachineBasicBlock::iterator MII = lis_.getInstructionFromIndex(Idx);
695   MachineBasicBlock *MBB = MII->getParent();
696   VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI, *MBB,
697                                      llvm::next(MII));
698
699   // Finally we must make sure that openli is properly extended from Idx to the
700   // new copy.
701   openli_.addSimpleRange(Idx.getBoundaryIndex(), VNI->def, ParentVNI);
702   DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
703 }
704
705 /// leaveIntvAtTop - Leave the interval at the top of MBB.
706 /// Currently, only one value can leave the interval.
707 void SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
708   assert(openli_.getLI() && "openIntv not called before leaveIntvAtTop");
709   SlotIndex Start = lis_.getMBBStartIdx(&MBB);
710   DEBUG(dbgs() << "    leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start);
711
712   VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Start);
713   if (!ParentVNI) {
714     DEBUG(dbgs() << ": not live\n");
715     return;
716   }
717
718   // We are going to insert a back copy, so we must have a dupli_.
719   VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI,
720                                      MBB, MBB.begin());
721
722   // Finally we must make sure that openli is properly extended from Start to
723   // the new copy.
724   openli_.addSimpleRange(Start, VNI->def, ParentVNI);
725   DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
726 }
727
728 /// closeIntv - Indicate that we are done editing the currently open
729 /// LiveInterval, and ranges can be trimmed.
730 void SplitEditor::closeIntv() {
731   assert(openli_.getLI() && "openIntv not called before closeIntv");
732
733   DEBUG(dbgs() << "    closeIntv cleaning up\n");
734   DEBUG(dbgs() << "    open " << *openli_.getLI() << '\n');
735   openli_.reset(0);
736 }
737
738 /// rewrite - Rewrite all uses of reg to use the new registers.
739 void SplitEditor::rewrite(unsigned reg) {
740   for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(reg),
741        RE = mri_.reg_end(); RI != RE;) {
742     MachineOperand &MO = RI.getOperand();
743     MachineInstr *MI = MO.getParent();
744     ++RI;
745     if (MI->isDebugValue()) {
746       DEBUG(dbgs() << "Zapping " << *MI);
747       // FIXME: We can do much better with debug values.
748       MO.setReg(0);
749       continue;
750     }
751     SlotIndex Idx = lis_.getInstructionIndex(MI);
752     Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
753     LiveInterval *LI = 0;
754     for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E;
755          ++I) {
756       LiveInterval *testli = *I;
757       if (testli->liveAt(Idx)) {
758         LI = testli;
759         break;
760       }
761     }
762     DEBUG(dbgs() << "  rewr BB#" << MI->getParent()->getNumber() << '\t'<< Idx);
763     assert(LI && "No register was live at use");
764     MO.setReg(LI->reg);
765     DEBUG(dbgs() << '\t' << *MI);
766   }
767 }
768
769 void
770 SplitEditor::addTruncSimpleRange(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
771   // Build vector of iterator pairs from the intervals.
772   typedef std::pair<LiveInterval::const_iterator,
773                     LiveInterval::const_iterator> IIPair;
774   SmallVector<IIPair, 8> Iters;
775   for (LiveRangeEdit::iterator LI = edit_.begin(), LE = edit_.end(); LI != LE;
776        ++LI) {
777     if (*LI == dupli_.getLI())
778       continue;
779     LiveInterval::const_iterator I = (*LI)->find(Start);
780     LiveInterval::const_iterator E = (*LI)->end();
781     if (I != E)
782       Iters.push_back(std::make_pair(I, E));
783   }
784
785   SlotIndex sidx = Start;
786   // Break [Start;End) into segments that don't overlap any intervals.
787   for (;;) {
788     SlotIndex next = sidx, eidx = End;
789     // Find overlapping intervals.
790     for (unsigned i = 0; i != Iters.size() && sidx < eidx; ++i) {
791       LiveInterval::const_iterator I = Iters[i].first;
792       // Interval I is overlapping [sidx;eidx). Trim sidx.
793       if (I->start <= sidx) {
794         sidx = I->end;
795         // Move to the next run, remove iters when all are consumed.
796         I = ++Iters[i].first;
797         if (I == Iters[i].second) {
798           Iters.erase(Iters.begin() + i);
799           --i;
800           continue;
801         }
802       }
803       // Trim eidx too if needed.
804       if (I->start >= eidx)
805         continue;
806       eidx = I->start;
807       next = I->end;
808     }
809     // Now, [sidx;eidx) doesn't overlap anything in intervals_.
810     if (sidx < eidx)
811       dupli_.addSimpleRange(sidx, eidx, VNI);
812     // If the interval end was truncated, we can try again from next.
813     if (next <= sidx)
814       break;
815     sidx = next;
816   }
817 }
818
819 void SplitEditor::computeRemainder() {
820   // First we need to fill in the live ranges in dupli.
821   // If values were redefined, we need a full recoloring with SSA update.
822   // If values were truncated, we only need to truncate the ranges.
823   // If values were partially rematted, we should shrink to uses.
824   // If values were fully rematted, they should be omitted.
825   // FIXME: If a single value is redefined, just move the def and truncate.
826   LiveInterval &parent = edit_.getParent();
827
828   // Values that are fully contained in the split intervals.
829   SmallPtrSet<const VNInfo*, 8> deadValues;
830   // Map all curli values that should have live defs in dupli.
831   for (LiveInterval::const_vni_iterator I = parent.vni_begin(),
832        E = parent.vni_end(); I != E; ++I) {
833     const VNInfo *VNI = *I;
834     // Original def is contained in the split intervals.
835     if (intervalsLiveAt(VNI->def)) {
836       // Did this value escape?
837       if (dupli_.isMapped(VNI))
838         truncatedValues.insert(VNI);
839       else
840         deadValues.insert(VNI);
841       continue;
842     }
843     // Add minimal live range at the definition.
844     VNInfo *DVNI = dupli_.defValue(VNI, VNI->def);
845     dupli_.getLI()->addRange(LiveRange(VNI->def, VNI->def.getNextSlot(), DVNI));
846   }
847
848   // Add all ranges to dupli.
849   for (LiveInterval::const_iterator I = parent.begin(), E = parent.end();
850        I != E; ++I) {
851     const LiveRange &LR = *I;
852     if (truncatedValues.count(LR.valno)) {
853       // recolor after removing intervals_.
854       addTruncSimpleRange(LR.start, LR.end, LR.valno);
855     } else if (!deadValues.count(LR.valno)) {
856       // recolor without truncation.
857       dupli_.addSimpleRange(LR.start, LR.end, LR.valno);
858     }
859   }
860 }
861
862 void SplitEditor::finish() {
863   assert(!openli_.getLI() && "Previous LI not closed before rewrite");
864   assert(dupli_.getLI() && "No dupli for rewrite. Noop spilt?");
865
866   // Complete dupli liveness.
867   computeRemainder();
868
869   // Get rid of unused values and set phi-kill flags.
870   dupli_.getLI()->RenumberValues(lis_);
871
872   // Now check if dupli was separated into multiple connected components.
873   ConnectedVNInfoEqClasses ConEQ(lis_);
874   if (unsigned NumComp = ConEQ.Classify(dupli_.getLI())) {
875     DEBUG(dbgs() << "  Remainder has " << NumComp << " connected components: "
876                  << *dupli_.getLI() << '\n');
877     // Did the remainder break up? Create intervals for all the components.
878     if (NumComp > 1) {
879       SmallVector<LiveInterval*, 8> dups;
880       dups.push_back(dupli_.getLI());
881       for (unsigned i = 1; i != NumComp; ++i)
882         dups.push_back(&edit_.create(mri_, lis_, vrm_));
883       ConEQ.Distribute(&dups[0]);
884       // Rewrite uses to the new regs.
885       rewrite(dupli_.getLI()->reg);
886     }
887   }
888
889   // Rewrite instructions.
890   rewrite(edit_.getReg());
891
892   // Calculate spill weight and allocation hints for new intervals.
893   VirtRegAuxInfo vrai(vrm_.getMachineFunction(), lis_, sa_.loops_);
894   for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I){
895     LiveInterval &li = **I;
896     vrai.CalculateRegClass(li.reg);
897     vrai.CalculateWeightAndHint(li);
898     DEBUG(dbgs() << "  new interval " << mri_.getRegClass(li.reg)->getName()
899                  << ":" << li << '\n');
900   }
901 }
902
903
904 //===----------------------------------------------------------------------===//
905 //                               Loop Splitting
906 //===----------------------------------------------------------------------===//
907
908 void SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
909   SplitAnalysis::LoopBlocks Blocks;
910   sa_.getLoopBlocks(Loop, Blocks);
911
912   DEBUG({
913     dbgs() << "  splitAround"; sa_.print(Blocks, dbgs()); dbgs() << '\n';
914   });
915
916   // Break critical edges as needed.
917   SplitAnalysis::BlockPtrSet CriticalExits;
918   sa_.getCriticalExits(Blocks, CriticalExits);
919   assert(CriticalExits.empty() && "Cannot break critical exits yet");
920
921   // Create new live interval for the loop.
922   openIntv();
923
924   // Insert copies in the predecessors.
925   for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
926        E = Blocks.Preds.end(); I != E; ++I) {
927     MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
928     enterIntvAtEnd(MBB);
929   }
930
931   // Switch all loop blocks.
932   for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
933        E = Blocks.Loop.end(); I != E; ++I)
934      useIntv(**I);
935
936   // Insert back copies in the exit blocks.
937   for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
938        E = Blocks.Exits.end(); I != E; ++I) {
939     MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
940     leaveIntvAtTop(MBB);
941   }
942
943   // Done.
944   closeIntv();
945   finish();
946 }
947
948
949 //===----------------------------------------------------------------------===//
950 //                            Single Block Splitting
951 //===----------------------------------------------------------------------===//
952
953 /// splitSingleBlocks - Split curli into a separate live interval inside each
954 /// basic block in Blocks.
955 void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
956   DEBUG(dbgs() << "  splitSingleBlocks for " << Blocks.size() << " blocks.\n");
957   // Determine the first and last instruction using curli in each block.
958   typedef std::pair<SlotIndex,SlotIndex> IndexPair;
959   typedef DenseMap<const MachineBasicBlock*,IndexPair> IndexPairMap;
960   IndexPairMap MBBRange;
961   for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
962        E = sa_.usingInstrs_.end(); I != E; ++I) {
963     const MachineBasicBlock *MBB = (*I)->getParent();
964     if (!Blocks.count(MBB))
965       continue;
966     SlotIndex Idx = lis_.getInstructionIndex(*I);
967     DEBUG(dbgs() << "  BB#" << MBB->getNumber() << '\t' << Idx << '\t' << **I);
968     IndexPair &IP = MBBRange[MBB];
969     if (!IP.first.isValid() || Idx < IP.first)
970       IP.first = Idx;
971     if (!IP.second.isValid() || Idx > IP.second)
972       IP.second = Idx;
973   }
974
975   // Create a new interval for each block.
976   for (SplitAnalysis::BlockPtrSet::const_iterator I = Blocks.begin(),
977        E = Blocks.end(); I != E; ++I) {
978     IndexPair &IP = MBBRange[*I];
979     DEBUG(dbgs() << "  splitting for BB#" << (*I)->getNumber() << ": ["
980                  << IP.first << ';' << IP.second << ")\n");
981     assert(IP.first.isValid() && IP.second.isValid());
982
983     openIntv();
984     enterIntvBefore(IP.first);
985     useIntv(IP.first.getBaseIndex(), IP.second.getBoundaryIndex());
986     leaveIntvAfter(IP.second);
987     closeIntv();
988   }
989   finish();
990 }
991
992
993 //===----------------------------------------------------------------------===//
994 //                            Sub Block Splitting
995 //===----------------------------------------------------------------------===//
996
997 /// getBlockForInsideSplit - If curli is contained inside a single basic block,
998 /// and it wou pay to subdivide the interval inside that block, return it.
999 /// Otherwise return NULL. The returned block can be passed to
1000 /// SplitEditor::splitInsideBlock.
1001 const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
1002   // The interval must be exclusive to one block.
1003   if (usingBlocks_.size() != 1)
1004     return 0;
1005   // Don't to this for less than 4 instructions. We want to be sure that
1006   // splitting actually reduces the instruction count per interval.
1007   if (usingInstrs_.size() < 4)
1008     return 0;
1009   return usingBlocks_.begin()->first;
1010 }
1011
1012 /// splitInsideBlock - Split curli into multiple intervals inside MBB.
1013 void SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
1014   SmallVector<SlotIndex, 32> Uses;
1015   Uses.reserve(sa_.usingInstrs_.size());
1016   for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1017        E = sa_.usingInstrs_.end(); I != E; ++I)
1018     if ((*I)->getParent() == MBB)
1019       Uses.push_back(lis_.getInstructionIndex(*I));
1020   DEBUG(dbgs() << "  splitInsideBlock BB#" << MBB->getNumber() << " for "
1021                << Uses.size() << " instructions.\n");
1022   assert(Uses.size() >= 3 && "Need at least 3 instructions");
1023   array_pod_sort(Uses.begin(), Uses.end());
1024
1025   // Simple algorithm: Find the largest gap between uses as determined by slot
1026   // indices. Create new intervals for instructions before the gap and after the
1027   // gap.
1028   unsigned bestPos = 0;
1029   int bestGap = 0;
1030   DEBUG(dbgs() << "    dist (" << Uses[0]);
1031   for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
1032     int g = Uses[i-1].distance(Uses[i]);
1033     DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
1034     if (g > bestGap)
1035       bestPos = i, bestGap = g;
1036   }
1037   DEBUG(dbgs() << "), best: -" << bestGap << "-\n");
1038
1039   // bestPos points to the first use after the best gap.
1040   assert(bestPos > 0 && "Invalid gap");
1041
1042   // FIXME: Don't create intervals for low densities.
1043
1044   // First interval before the gap. Don't create single-instr intervals.
1045   if (bestPos > 1) {
1046     openIntv();
1047     enterIntvBefore(Uses.front());
1048     useIntv(Uses.front().getBaseIndex(), Uses[bestPos-1].getBoundaryIndex());
1049     leaveIntvAfter(Uses[bestPos-1]);
1050     closeIntv();
1051   }
1052
1053   // Second interval after the gap.
1054   if (bestPos < Uses.size()-1) {
1055     openIntv();
1056     enterIntvBefore(Uses[bestPos]);
1057     useIntv(Uses[bestPos].getBaseIndex(), Uses.back().getBoundaryIndex());
1058     leaveIntvAfter(Uses.back());
1059     closeIntv();
1060   }
1061
1062   finish();
1063 }