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 "VirtRegMap.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineLoopInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 
29 using namespace llvm;
30 
31 static cl::opt<bool>
32 AllowSplit("spiller-splits-edges",
33            cl::desc("Allow critical edge splitting during spilling"));
34 
35 //===----------------------------------------------------------------------===//
36 //                                 Split Analysis
37 //===----------------------------------------------------------------------===//
38 
39 SplitAnalysis::SplitAnalysis(const MachineFunction &mf,
40                              const LiveIntervals &lis,
41                              const MachineLoopInfo &mli)
42   : mf_(mf),
43     lis_(lis),
44     loops_(mli),
45     tii_(*mf.getTarget().getInstrInfo()),
46     curli_(0) {}
47 
48 void SplitAnalysis::clear() {
49   usingInstrs_.clear();
50   usingBlocks_.clear();
51   usingLoops_.clear();
52   curli_ = 0;
53 }
54 
55 bool SplitAnalysis::canAnalyzeBranch(const MachineBasicBlock *MBB) {
56   MachineBasicBlock *T, *F;
57   SmallVector<MachineOperand, 4> Cond;
58   return !tii_.AnalyzeBranch(const_cast<MachineBasicBlock&>(*MBB), T, F, Cond);
59 }
60 
61 /// analyzeUses - Count instructions, basic blocks, and loops using curli.
62 void SplitAnalysis::analyzeUses() {
63   const MachineRegisterInfo &MRI = mf_.getRegInfo();
64   for (MachineRegisterInfo::reg_iterator I = MRI.reg_begin(curli_->reg);
65        MachineInstr *MI = I.skipInstruction();) {
66     if (MI->isDebugValue() || !usingInstrs_.insert(MI))
67       continue;
68     MachineBasicBlock *MBB = MI->getParent();
69     if (usingBlocks_[MBB]++)
70       continue;
71     if (MachineLoop *Loop = loops_.getLoopFor(MBB))
72       usingLoops_.insert(Loop);
73   }
74   DEBUG(dbgs() << "Counted "
75                << usingInstrs_.size() << " instrs, "
76                << usingBlocks_.size() << " blocks, "
77                << usingLoops_.size()  << " loops in "
78                << *curli_ << "\n");
79 }
80 
81 // Get three sets of basic blocks surrounding a loop: Blocks inside the loop,
82 // predecessor blocks, and exit blocks.
83 void SplitAnalysis::getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks) {
84   Blocks.clear();
85 
86   // Blocks in the loop.
87   Blocks.Loop.insert(Loop->block_begin(), Loop->block_end());
88 
89   // Predecessor blocks.
90   const MachineBasicBlock *Header = Loop->getHeader();
91   for (MachineBasicBlock::const_pred_iterator I = Header->pred_begin(),
92        E = Header->pred_end(); I != E; ++I)
93     if (!Blocks.Loop.count(*I))
94       Blocks.Preds.insert(*I);
95 
96   // Exit blocks.
97   for (MachineLoop::block_iterator I = Loop->block_begin(),
98        E = Loop->block_end(); I != E; ++I) {
99     const MachineBasicBlock *MBB = *I;
100     for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
101        SE = MBB->succ_end(); SI != SE; ++SI)
102       if (!Blocks.Loop.count(*SI))
103         Blocks.Exits.insert(*SI);
104   }
105 }
106 
107 /// analyzeLoopPeripheralUse - Return an enum describing how curli_ is used in
108 /// and around the Loop.
109 SplitAnalysis::LoopPeripheralUse SplitAnalysis::
110 analyzeLoopPeripheralUse(const SplitAnalysis::LoopBlocks &Blocks) {
111   LoopPeripheralUse use = ContainedInLoop;
112   for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
113        I != E; ++I) {
114     const MachineBasicBlock *MBB = I->first;
115     // Is this a peripheral block?
116     if (use < MultiPeripheral &&
117         (Blocks.Preds.count(MBB) || Blocks.Exits.count(MBB))) {
118       if (I->second > 1) use = MultiPeripheral;
119       else               use = SinglePeripheral;
120       continue;
121     }
122     // Is it a loop block?
123     if (Blocks.Loop.count(MBB))
124       continue;
125     // It must be an unrelated block.
126     return OutsideLoop;
127   }
128   return use;
129 }
130 
131 /// getCriticalExits - It may be necessary to partially break critical edges
132 /// leaving the loop if an exit block has phi uses of curli. Collect the exit
133 /// blocks that need special treatment into CriticalExits.
134 void SplitAnalysis::getCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
135                                      BlockPtrSet &CriticalExits) {
136   CriticalExits.clear();
137 
138   // A critical exit block contains a phi def of curli, and has a predecessor
139   // that is not in the loop nor a loop predecessor.
140   // For such an exit block, the edges carrying the new variable must be moved
141   // to a new pre-exit block.
142   for (BlockPtrSet::iterator I = Blocks.Exits.begin(), E = Blocks.Exits.end();
143        I != E; ++I) {
144     const MachineBasicBlock *Succ = *I;
145     SlotIndex SuccIdx = lis_.getMBBStartIdx(Succ);
146     VNInfo *SuccVNI = curli_->getVNInfoAt(SuccIdx);
147     // This exit may not have curli live in at all. No need to split.
148     if (!SuccVNI)
149       continue;
150     // If this is not a PHI def, it is either using a value from before the
151     // loop, or a value defined inside the loop. Both are safe.
152     if (!SuccVNI->isPHIDef() || SuccVNI->def.getBaseIndex() != SuccIdx)
153       continue;
154     // This exit block does have a PHI. Does it also have a predecessor that is
155     // not a loop block or loop predecessor?
156     for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
157          PE = Succ->pred_end(); PI != PE; ++PI) {
158       const MachineBasicBlock *Pred = *PI;
159       if (Blocks.Loop.count(Pred) || Blocks.Preds.count(Pred))
160         continue;
161       // This is a critical exit block, and we need to split the exit edge.
162       CriticalExits.insert(Succ);
163       break;
164     }
165   }
166 }
167 
168 /// canSplitCriticalExits - Return true if it is possible to insert new exit
169 /// blocks before the blocks in CriticalExits.
170 bool
171 SplitAnalysis::canSplitCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
172                                      BlockPtrSet &CriticalExits) {
173   // If we don't allow critical edge splitting, require no critical exits.
174   if (!AllowSplit)
175     return CriticalExits.empty();
176 
177   for (BlockPtrSet::iterator I = CriticalExits.begin(), E = CriticalExits.end();
178        I != E; ++I) {
179     const MachineBasicBlock *Succ = *I;
180     // We want to insert a new pre-exit MBB before Succ, and change all the
181     // in-loop blocks to branch to the pre-exit instead of Succ.
182     // Check that all the in-loop predecessors can be changed.
183     for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
184          PE = Succ->pred_end(); PI != PE; ++PI) {
185       const MachineBasicBlock *Pred = *PI;
186       // The external predecessors won't be altered.
187       if (!Blocks.Loop.count(Pred) && !Blocks.Preds.count(Pred))
188         continue;
189       if (!canAnalyzeBranch(Pred))
190         return false;
191     }
192 
193     // If Succ's layout predecessor falls through, that too must be analyzable.
194     // We need to insert the pre-exit block in the gap.
195     MachineFunction::const_iterator MFI = Succ;
196     if (MFI == mf_.begin())
197       continue;
198     if (!canAnalyzeBranch(--MFI))
199       return false;
200   }
201   // No problems found.
202   return true;
203 }
204 
205 void SplitAnalysis::analyze(const LiveInterval *li) {
206   clear();
207   curli_ = li;
208   analyzeUses();
209 }
210 
211 const MachineLoop *SplitAnalysis::getBestSplitLoop() {
212   assert(curli_ && "Call analyze() before getBestSplitLoop");
213   if (usingLoops_.empty())
214     return 0;
215 
216   LoopPtrSet Loops, SecondLoops;
217   LoopBlocks Blocks;
218   BlockPtrSet CriticalExits;
219 
220   // Find first-class and second class candidate loops.
221   // We prefer to split around loops where curli is used outside the periphery.
222   for (LoopPtrSet::const_iterator I = usingLoops_.begin(),
223        E = usingLoops_.end(); I != E; ++I) {
224     getLoopBlocks(*I, Blocks);
225     LoopPtrSet *LPS = 0;
226     switch(analyzeLoopPeripheralUse(Blocks)) {
227     case OutsideLoop:
228       LPS = &Loops;
229       break;
230     case MultiPeripheral:
231       LPS = &SecondLoops;
232       break;
233     case ContainedInLoop:
234       DEBUG(dbgs() << "ContainedInLoop: " << **I);
235       continue;
236     case SinglePeripheral:
237       DEBUG(dbgs() << "SinglePeripheral: " << **I);
238       continue;
239     }
240     // Will it be possible to split around this loop?
241     getCriticalExits(Blocks, CriticalExits);
242     DEBUG(dbgs() << CriticalExits.size() << " critical exits: " << **I);
243     if (!canSplitCriticalExits(Blocks, CriticalExits))
244       continue;
245     // This is a possible split.
246     assert(LPS);
247     LPS->insert(*I);
248   }
249 
250   DEBUG(dbgs() << "Got " << Loops.size() << " + " << SecondLoops.size()
251                << " candidate loops\n");
252 
253   // If there are no first class loops available, look at second class loops.
254   if (Loops.empty())
255     Loops = SecondLoops;
256 
257   if (Loops.empty())
258     return 0;
259 
260   // Pick the earliest loop.
261   // FIXME: Are there other heuristics to consider?
262   const MachineLoop *Best = 0;
263   SlotIndex BestIdx;
264   for (LoopPtrSet::const_iterator I = Loops.begin(), E = Loops.end(); I != E;
265        ++I) {
266     SlotIndex Idx = lis_.getMBBStartIdx((*I)->getHeader());
267     if (!Best || Idx < BestIdx)
268       Best = *I, BestIdx = Idx;
269   }
270   DEBUG(dbgs() << "Best: " << *Best);
271   return Best;
272 }
273 
274 
275 //===----------------------------------------------------------------------===//
276 //                               Split Editor
277 //===----------------------------------------------------------------------===//
278 
279 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
280 SplitEditor::SplitEditor(SplitAnalysis &sa, LiveIntervals &lis, VirtRegMap &vrm)
281   : sa_(sa), lis_(lis), vrm_(vrm),
282     mri_(vrm.getMachineFunction().getRegInfo()),
283     tii_(*vrm.getMachineFunction().getTarget().getInstrInfo()),
284     dupli_(0), openli_(0)
285 {
286   const LiveInterval *curli = sa_.getCurLI();
287   assert(curli && "SplitEditor created from empty SplitAnalysis");
288 
289   // Make sure curli is assigned a stack slot, so all our intervals get the
290   // same slot as curli.
291   if (vrm_.getStackSlot(curli->reg) == VirtRegMap::NO_STACK_SLOT)
292     vrm_.assignVirt2StackSlot(curli->reg);
293 
294   // Create an interval for dupli that is a copy of curli.
295   dupli_ = createInterval();
296   dupli_->Copy(*curli, &mri_, lis_.getVNInfoAllocator());
297   DEBUG(dbgs() << "SplitEditor DupLI: " << *dupli_ << '\n');
298 }
299 
300 LiveInterval *SplitEditor::createInterval() {
301   unsigned curli = sa_.getCurLI()->reg;
302   unsigned Reg = mri_.createVirtualRegister(mri_.getRegClass(curli));
303   LiveInterval &Intv = lis_.getOrCreateInterval(Reg);
304   vrm_.grow();
305   vrm_.assignVirt2StackSlot(Reg, vrm_.getStackSlot(curli));
306   return &Intv;
307 }
308 
309 VNInfo *SplitEditor::mapValue(VNInfo *dupliVNI) {
310   VNInfo *&VNI = valueMap_[dupliVNI];
311   if (!VNI)
312     VNI = openli_->createValueCopy(dupliVNI, lis_.getVNInfoAllocator());
313   return VNI;
314 }
315 
316 /// Create a new virtual register and live interval to be used by following
317 /// use* and copy* calls.
318 void SplitEditor::openLI() {
319   assert(!openli_ && "Previous LI not closed before openLI");
320   openli_ = createInterval();
321 }
322 
323 /// copyToPHI - Insert a copy to openli at the end of A, and catch it with a
324 /// PHI def at the beginning of the successor B. This call is ignored if dupli
325 /// is not live out of A.
326 void SplitEditor::copyToPHI(MachineBasicBlock &A, MachineBasicBlock &B) {
327   assert(openli_ && "openLI not called before copyToPHI");
328 
329   SlotIndex EndA = lis_.getMBBEndIdx(&A);
330   VNInfo *DupVNIA = dupli_->getVNInfoAt(EndA.getPrevIndex());
331   if (!DupVNIA) {
332     DEBUG(dbgs() << "  ignoring copyToPHI, dupli not live out of BB#"
333                  << A.getNumber() << ".\n");
334     return;
335   }
336 
337   // Insert the COPY instruction at the end of A.
338   MachineInstr *MI = BuildMI(A, A.getFirstTerminator(), DebugLoc(),
339                                  tii_.get(TargetOpcode::COPY), dupli_->reg)
340                            .addReg(openli_->reg);
341   SlotIndex DefIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
342 
343   // Add a phi kill value and live range out of A.
344   VNInfo *VNIA = openli_->getNextValue(DefIdx, MI, true,
345                                        lis_.getVNInfoAllocator());
346   openli_->addRange(LiveRange(DefIdx, EndA, VNIA));
347 
348   // Now look at the start of B.
349   SlotIndex StartB = lis_.getMBBStartIdx(&B);
350   SlotIndex EndB = lis_.getMBBEndIdx(&B);
351   LiveRange *DupB = dupli_->getLiveRangeContaining(StartB);
352   if (!DupB) {
353     DEBUG(dbgs() << "  copyToPHI:, dupli not live in to BB#"
354                  << B.getNumber() << ".\n");
355     return;
356   }
357 
358   VNInfo *VNIB = openli_->getVNInfoAt(StartB);
359   if (!VNIB) {
360     // Create a phi value.
361     VNIB = openli_->getNextValue(SlotIndex(StartB, true), 0, false,
362                                  lis_.getVNInfoAllocator());
363     VNIB->setIsPHIDef(true);
364     // Add a minimal range for the new value.
365     openli_->addRange(LiveRange(VNIB->def, std::min(EndB, DupB->end), VNIB));
366 
367     VNInfo *&mapVNI = valueMap_[DupB->valno];
368     if (mapVNI) {
369       // Multiple copies - must create PHI value.
370       abort();
371     } else {
372       // This is the first copy of dupLR. Mark the mapping.
373       mapVNI = VNIB;
374     }
375 
376   }
377 
378   DEBUG(dbgs() << "  copyToPHI at " << DefIdx << ": " << *openli_ << '\n');
379 }
380 
381 /// useLI - indicate that all instructions in MBB should use openli.
382 void SplitEditor::useLI(const MachineBasicBlock &MBB) {
383   useLI(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB));
384 }
385 
386 void SplitEditor::useLI(SlotIndex Start, SlotIndex End) {
387   assert(openli_ && "openLI not called before useLI");
388 
389   // Map the dupli values from the interval into openli_
390   LiveInterval::const_iterator B = dupli_->begin(), E = dupli_->end();
391   LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
392 
393   if (I != B) {
394     --I;
395     // I begins before Start, but overlaps. openli may already have a value from
396     // copyToLI.
397     if (I->end > Start && !openli_->liveAt(Start))
398       openli_->addRange(LiveRange(Start, std::min(End, I->end),
399                         mapValue(I->valno)));
400     ++I;
401   }
402 
403   // The remaining ranges begin after Start.
404   for (;I != E && I->start < End; ++I)
405     openli_->addRange(LiveRange(I->start, std::min(End, I->end),
406                                 mapValue(I->valno)));
407   DEBUG(dbgs() << "  added range [" << Start << ';' << End << "): " << *openli_
408                << '\n');
409 }
410 
411 /// copyFromLI - Insert a copy back to dupli from openli at position I.
412 SlotIndex SplitEditor::copyFromLI(MachineBasicBlock &MBB, MachineBasicBlock::iterator I) {
413   assert(openli_ && "openLI not called before copyFromLI");
414 
415   // Insert the COPY instruction.
416   MachineInstr *MI =
417     BuildMI(MBB, I, DebugLoc(), tii_.get(TargetOpcode::COPY), openli_->reg)
418       .addReg(dupli_->reg);
419   SlotIndex Idx = lis_.InsertMachineInstrInMaps(MI);
420 
421   DEBUG(dbgs() << "  copyFromLI at " << Idx << ": " << *openli_ << '\n');
422   return Idx;
423 }
424 
425 /// closeLI - Indicate that we are done editing the currently open
426 /// LiveInterval, and ranges can be trimmed.
427 void SplitEditor::closeLI() {
428   assert(openli_ && "openLI not called before closeLI");
429   openli_ = 0;
430 }
431 
432 /// rewrite - after all the new live ranges have been created, rewrite
433 /// instructions using curli to use the new intervals.
434 void SplitEditor::rewrite() {
435   assert(!openli_ && "Previous LI not closed before rewrite");
436 }
437 
438 
439 //===----------------------------------------------------------------------===//
440 //                               Loop Splitting
441 //===----------------------------------------------------------------------===//
442 
443 void SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
444   SplitAnalysis::LoopBlocks Blocks;
445   sa_.getLoopBlocks(Loop, Blocks);
446 
447   // Break critical edges as needed.
448   SplitAnalysis::BlockPtrSet CriticalExits;
449   sa_.getCriticalExits(Blocks, CriticalExits);
450   assert(CriticalExits.empty() && "Cannot break critical exits yet");
451 
452   // Create new live interval for the loop.
453   openLI();
454 
455   // Insert copies in the predecessors.
456   for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
457        E = Blocks.Preds.end(); I != E; ++I) {
458     MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
459     copyToPHI(MBB, *Loop->getHeader());
460   }
461 
462   // Switch all loop blocks.
463   for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
464        E = Blocks.Loop.end(); I != E; ++I)
465      useLI(**I);
466 
467   // Insert back copies in the exit blocks.
468   for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
469        E = Blocks.Exits.end(); I != E; ++I) {
470     MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
471     SlotIndex Start = lis_.getMBBStartIdx(&MBB);
472     VNInfo *VNI = sa_.getCurLI()->getVNInfoAt(Start);
473     // Only insert a back copy if curli is live and is either a phi or a value
474     // defined inside the loop.
475     if (!VNI) continue;
476     if (openli_->liveAt(VNI->def) ||
477         (VNI->isPHIDef() && VNI->def.getBaseIndex() == Start))
478       copyFromLI(MBB, MBB.begin());
479   }
480 
481   // Done.
482   closeLI();
483   rewrite();
484   abort();
485 }
486 
487