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