blob: 2ab7fa83e51a3eb2673ce9f548b5a0ea766ce4fb [file] [log] [blame]
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +00001//===---------- 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"
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +000017#include "VirtRegMap.h"
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +000018#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000019#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +000020#include "llvm/CodeGen/MachineInstrBuilder.h"
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000021#include "llvm/CodeGen/MachineLoopInfo.h"
22#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000023#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000024#include "llvm/Support/Debug.h"
25#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000026#include "llvm/Target/TargetInstrInfo.h"
27#include "llvm/Target/TargetMachine.h"
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000028
29using namespace llvm;
30
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000031static cl::opt<bool>
32AllowSplit("spiller-splits-edges",
33 cl::desc("Allow critical edge splitting during spilling"));
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000034
35//===----------------------------------------------------------------------===//
36// Split Analysis
37//===----------------------------------------------------------------------===//
38
Jakob Stoklund Olesenf2c6e362010-07-20 23:50:15 +000039SplitAnalysis::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()),
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000046 curli_(0) {}
47
48void SplitAnalysis::clear() {
49 usingInstrs_.clear();
50 usingBlocks_.clear();
51 usingLoops_.clear();
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +000052 curli_ = 0;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000053}
54
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000055bool 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
Jakob Stoklund Olesenabff2802010-07-20 16:12:37 +000061/// analyzeUses - Count instructions, basic blocks, and loops using curli.
62void SplitAnalysis::analyzeUses() {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000063 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;
Jakob Stoklund Olesen9b90d7e2010-10-05 23:10:12 +000071 for (MachineLoop *Loop = loops_.getLoopFor(MBB); Loop;
72 Loop = Loop->getParentLoop())
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +000073 usingLoops_[Loop]++;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000074 }
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +000075 DEBUG(dbgs() << " counted "
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000076 << usingInstrs_.size() << " instrs, "
77 << usingBlocks_.size() << " blocks, "
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +000078 << usingLoops_.size() << " loops.\n");
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000079}
80
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000081// Get three sets of basic blocks surrounding a loop: Blocks inside the loop,
82// predecessor blocks, and exit blocks.
83void SplitAnalysis::getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks) {
84 Blocks.clear();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000085
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000086 // 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.
109SplitAnalysis::LoopPeripheralUse SplitAnalysis::
110analyzeLoopPeripheralUse(const SplitAnalysis::LoopBlocks &Blocks) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000111 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 &&
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000117 (Blocks.Preds.count(MBB) || Blocks.Exits.count(MBB))) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000118 if (I->second > 1) use = MultiPeripheral;
119 else use = SinglePeripheral;
120 continue;
121 }
122 // Is it a loop block?
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000123 if (Blocks.Loop.count(MBB))
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000124 continue;
125 // It must be an unrelated block.
126 return OutsideLoop;
127 }
128 return use;
129}
130
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000131/// 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.
134void 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.
170bool
171SplitAnalysis::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
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000205void SplitAnalysis::analyze(const LiveInterval *li) {
206 clear();
207 curli_ = li;
Jakob Stoklund Olesenabff2802010-07-20 16:12:37 +0000208 analyzeUses();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000209}
210
211const MachineLoop *SplitAnalysis::getBestSplitLoop() {
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000212 assert(curli_ && "Call analyze() before getBestSplitLoop");
213 if (usingLoops_.empty())
214 return 0;
215
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000216 LoopPtrSet Loops;
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000217 LoopBlocks Blocks;
218 BlockPtrSet CriticalExits;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000219
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000220 // We split around loops where curli is used outside the periphery.
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000221 for (LoopCountMap::const_iterator I = usingLoops_.begin(),
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000222 E = usingLoops_.end(); I != E; ++I) {
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000223 const MachineLoop *Loop = I->first;
224 getLoopBlocks(Loop, Blocks);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000225
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000226 switch(analyzeLoopPeripheralUse(Blocks)) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000227 case OutsideLoop:
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000228 break;
229 case MultiPeripheral:
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000230 // FIXME: We could split a live range with multiple uses in a peripheral
231 // block and still make progress. However, it is possible that splitting
232 // another live range will insert copies into a peripheral block, and
233 // there is a small chance we can enter an infinity loop, inserting copies
234 // forever.
235 // For safety, stick to splitting live ranges with uses outside the
236 // periphery.
237 DEBUG(dbgs() << " multiple peripheral uses in " << *Loop);
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000238 break;
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000239 case ContainedInLoop:
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000240 DEBUG(dbgs() << " contained in " << *Loop);
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000241 continue;
242 case SinglePeripheral:
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000243 DEBUG(dbgs() << " single peripheral use in " << *Loop);
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000244 continue;
245 }
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000246 // Will it be possible to split around this loop?
247 getCriticalExits(Blocks, CriticalExits);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000248 DEBUG(dbgs() << " " << CriticalExits.size() << " critical exits from "
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000249 << *Loop);
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000250 if (!canSplitCriticalExits(Blocks, CriticalExits))
251 continue;
252 // This is a possible split.
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000253 Loops.insert(Loop);
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000254 }
255
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000256 DEBUG(dbgs() << " getBestSplitLoop found " << Loops.size()
257 << " candidate loops.\n");
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000258
259 if (Loops.empty())
260 return 0;
261
262 // Pick the earliest loop.
263 // FIXME: Are there other heuristics to consider?
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000264 const MachineLoop *Best = 0;
265 SlotIndex BestIdx;
266 for (LoopPtrSet::const_iterator I = Loops.begin(), E = Loops.end(); I != E;
267 ++I) {
268 SlotIndex Idx = lis_.getMBBStartIdx((*I)->getHeader());
269 if (!Best || Idx < BestIdx)
270 Best = *I, BestIdx = Idx;
271 }
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000272 DEBUG(dbgs() << " getBestSplitLoop found " << *Best);
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000273 return Best;
274}
275
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000276/// getMultiUseBlocks - if curli has more than one use in a basic block, it
277/// may be an advantage to split curli for the duration of the block.
278bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
279 // If curli is local to one block, there is no point to splitting it.
280 if (usingBlocks_.size() <= 1)
281 return false;
282 // Add blocks with multiple uses.
283 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
284 I != E; ++I)
285 switch (I->second) {
286 case 0:
287 case 1:
288 continue;
289 case 2: {
290 // It doesn't pay to split a 2-instr block if it redefines curli.
291 VNInfo *VN1 = curli_->getVNInfoAt(lis_.getMBBStartIdx(I->first));
292 VNInfo *VN2 =
293 curli_->getVNInfoAt(lis_.getMBBEndIdx(I->first).getPrevIndex());
294 // live-in and live-out with a different value.
295 if (VN1 && VN2 && VN1 != VN2)
296 continue;
297 } // Fall through.
298 default:
299 Blocks.insert(I->first);
300 }
301 return !Blocks.empty();
302}
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000303
304//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000305// LiveIntervalMap
306//===----------------------------------------------------------------------===//
307
Jakob Stoklund Olesenb3e96812010-09-13 21:29:45 +0000308// Work around the fact that the std::pair constructors are broken for pointer
309// pairs in some implementations. makeVV(x, 0) works.
310static inline std::pair<const VNInfo*, VNInfo*>
311makeVV(const VNInfo *a, VNInfo *b) {
312 return std::make_pair(a, b);
313}
314
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000315void LiveIntervalMap::reset(LiveInterval *li) {
316 li_ = li;
317 valueMap_.clear();
318}
319
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000320bool LiveIntervalMap::isComplexMapped(const VNInfo *ParentVNI) const {
321 ValueMap::const_iterator i = valueMap_.find(ParentVNI);
322 return i != valueMap_.end() && i->second == 0;
323}
324
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000325// defValue - Introduce a li_ def for ParentVNI that could be later than
326// ParentVNI->def.
327VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000328 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000329 assert(ParentVNI && "Mapping NULL value");
330 assert(Idx.isValid() && "Invalid SlotIndex");
331 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
332
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000333 // Create a new value.
Lang Hames6e2968c2010-09-25 12:04:16 +0000334 VNInfo *VNI = li_->getNextValue(Idx, 0, lis_.getVNInfoAllocator());
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000335
336 // Use insert for lookup, so we can add missing values with a second lookup.
337 std::pair<ValueMap::iterator,bool> InsP =
338 valueMap_.insert(makeVV(ParentVNI, Idx == ParentVNI->def ? VNI : 0));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000339
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000340 // This is now a complex def. Mark with a NULL in valueMap.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000341 if (!InsP.second)
342 InsP.first->second = 0;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000343
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000344 return VNI;
345}
346
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000347
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000348// mapValue - Find the mapped value for ParentVNI at Idx.
349// Potentially create phi-def values.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000350VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx,
351 bool *simple) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000352 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000353 assert(ParentVNI && "Mapping NULL value");
354 assert(Idx.isValid() && "Invalid SlotIndex");
355 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
356
357 // Use insert for lookup, so we can add missing values with a second lookup.
358 std::pair<ValueMap::iterator,bool> InsP =
Jakob Stoklund Olesenb3e96812010-09-13 21:29:45 +0000359 valueMap_.insert(makeVV(ParentVNI, 0));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000360
361 // This was an unknown value. Create a simple mapping.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000362 if (InsP.second) {
363 if (simple) *simple = true;
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000364 return InsP.first->second = li_->createValueCopy(ParentVNI,
365 lis_.getVNInfoAllocator());
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000366 }
367
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000368 // This was a simple mapped value.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000369 if (InsP.first->second) {
370 if (simple) *simple = true;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000371 return InsP.first->second;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000372 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000373
374 // This is a complex mapped value. There may be multiple defs, and we may need
375 // to create phi-defs.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000376 if (simple) *simple = false;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000377 MachineBasicBlock *IdxMBB = lis_.getMBBFromIndex(Idx);
378 assert(IdxMBB && "No MBB at Idx");
379
380 // Is there a def in the same MBB we can extend?
381 if (VNInfo *VNI = extendTo(IdxMBB, Idx))
382 return VNI;
383
384 // Now for the fun part. We know that ParentVNI potentially has multiple defs,
385 // and we may need to create even more phi-defs to preserve VNInfo SSA form.
386 // Perform a depth-first search for predecessor blocks where we know the
387 // dominating VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
388
389 // Track MBBs where we have created or learned the dominating value.
390 // This may change during the DFS as we create new phi-defs.
391 typedef DenseMap<MachineBasicBlock*, VNInfo*> MBBValueMap;
392 MBBValueMap DomValue;
Jakob Stoklund Olesen984a7fc2010-10-05 20:36:28 +0000393 typedef SplitAnalysis::BlockPtrSet BlockPtrSet;
394 BlockPtrSet Visited;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000395
Jakob Stoklund Olesen984a7fc2010-10-05 20:36:28 +0000396 // Iterate over IdxMBB predecessors in a depth-first order.
397 // Skip begin() since that is always IdxMBB.
398 for (idf_ext_iterator<MachineBasicBlock*, BlockPtrSet>
399 IDFI = llvm::next(idf_ext_begin(IdxMBB, Visited)),
400 IDFE = idf_ext_end(IdxMBB, Visited); IDFI != IDFE;) {
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000401 MachineBasicBlock *MBB = *IDFI;
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000402 SlotIndex End = lis_.getMBBEndIdx(MBB).getPrevSlot();
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000403
404 // We are operating on the restricted CFG where ParentVNI is live.
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000405 if (parentli_.getVNInfoAt(End) != ParentVNI) {
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000406 IDFI.skipChildren();
407 continue;
408 }
409
410 // Do we have a dominating value in this block?
411 VNInfo *VNI = extendTo(MBB, End);
412 if (!VNI) {
413 ++IDFI;
414 continue;
415 }
416
Jakob Stoklund Olesen984a7fc2010-10-05 20:36:28 +0000417 // Yes, VNI dominates MBB. Make sure we visit MBB again from other paths.
418 Visited.erase(MBB);
419
420 // Track the path back to IdxMBB, creating phi-defs
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000421 // as needed along the way.
422 for (unsigned PI = IDFI.getPathLength()-1; PI != 0; --PI) {
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000423 // Start from MBB's immediate successor. End at IdxMBB.
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000424 MachineBasicBlock *Succ = IDFI.getPath(PI-1);
425 std::pair<MBBValueMap::iterator, bool> InsP =
426 DomValue.insert(MBBValueMap::value_type(Succ, VNI));
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000427
428 // This is the first time we backtrack to Succ.
429 if (InsP.second)
430 continue;
431
432 // We reached Succ again with the same VNI. Nothing is going to change.
433 VNInfo *OVNI = InsP.first->second;
434 if (OVNI == VNI)
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000435 break;
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000436
437 // Succ already has a phi-def. No need to continue.
438 SlotIndex Start = lis_.getMBBStartIdx(Succ);
439 if (OVNI->def == Start)
440 break;
441
442 // We have a collision between the old and new VNI at Succ. That means
443 // neither dominates and we need a new phi-def.
Lang Hames6e2968c2010-09-25 12:04:16 +0000444 VNI = li_->getNextValue(Start, 0, lis_.getVNInfoAllocator());
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000445 VNI->setIsPHIDef(true);
446 InsP.first->second = VNI;
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000447
448 // Replace OVNI with VNI in the remaining path.
449 for (; PI > 1 ; --PI) {
450 MBBValueMap::iterator I = DomValue.find(IDFI.getPath(PI-2));
451 if (I == DomValue.end() || I->second != OVNI)
452 break;
453 I->second = VNI;
454 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000455 }
456
457 // No need to search the children, we found a dominating value.
Jakob Stoklund Olesencf16bea2010-08-18 20:06:05 +0000458 IDFI.skipChildren();
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000459 }
460
461 // The search should at least find a dominating value for IdxMBB.
462 assert(!DomValue.empty() && "Couldn't find a reaching definition");
463
464 // Since we went through the trouble of a full DFS visiting all reaching defs,
465 // the values in DomValue are now accurate. No more phi-defs are needed for
466 // these blocks, so we can color the live ranges.
467 // This makes the next mapValue call much faster.
468 VNInfo *IdxVNI = 0;
469 for (MBBValueMap::iterator I = DomValue.begin(), E = DomValue.end(); I != E;
470 ++I) {
471 MachineBasicBlock *MBB = I->first;
472 VNInfo *VNI = I->second;
473 SlotIndex Start = lis_.getMBBStartIdx(MBB);
474 if (MBB == IdxMBB) {
475 // Don't add full liveness to IdxMBB, stop at Idx.
476 if (Start != Idx)
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000477 li_->addRange(LiveRange(Start, Idx.getNextSlot(), VNI));
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000478 // The caller had better add some liveness to IdxVNI, or it leaks.
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000479 IdxVNI = VNI;
480 } else
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000481 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000482 }
483
484 assert(IdxVNI && "Didn't find value for Idx");
485 return IdxVNI;
486}
487
488// extendTo - Find the last li_ value defined in MBB at or before Idx. The
489// parentli_ is assumed to be live at Idx. Extend the live range to Idx.
490// Return the found VNInfo, or NULL.
491VNInfo *LiveIntervalMap::extendTo(MachineBasicBlock *MBB, SlotIndex Idx) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000492 assert(li_ && "call reset first");
493 LiveInterval::iterator I = std::upper_bound(li_->begin(), li_->end(), Idx);
494 if (I == li_->begin())
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000495 return 0;
496 --I;
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000497 if (I->end <= lis_.getMBBStartIdx(MBB))
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000498 return 0;
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000499 if (I->end <= Idx)
500 I->end = Idx.getNextSlot();
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000501 return I->valno;
502}
503
504// addSimpleRange - Add a simple range from parentli_ to li_.
505// ParentVNI must be live in the [Start;End) interval.
506void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End,
507 const VNInfo *ParentVNI) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000508 assert(li_ && "call reset first");
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000509 bool simple;
510 VNInfo *VNI = mapValue(ParentVNI, Start, &simple);
511 // A simple mapping is easy.
512 if (simple) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000513 li_->addRange(LiveRange(Start, End, VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000514 return;
515 }
516
517 // ParentVNI is a complex value. We must map per MBB.
518 MachineFunction::iterator MBB = lis_.getMBBFromIndex(Start);
Jakob Stoklund Olesendbc36092010-10-05 22:19:29 +0000519 MachineFunction::iterator MBBE = lis_.getMBBFromIndex(End.getPrevSlot());
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000520
521 if (MBB == MBBE) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000522 li_->addRange(LiveRange(Start, End, VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000523 return;
524 }
525
526 // First block.
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000527 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000528
529 // Run sequence of full blocks.
530 for (++MBB; MBB != MBBE; ++MBB) {
531 Start = lis_.getMBBStartIdx(MBB);
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000532 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB),
533 mapValue(ParentVNI, Start)));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000534 }
535
536 // Final block.
537 Start = lis_.getMBBStartIdx(MBB);
538 if (Start != End)
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000539 li_->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start)));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000540}
541
542/// addRange - Add live ranges to li_ where [Start;End) intersects parentli_.
543/// All needed values whose def is not inside [Start;End) must be defined
544/// beforehand so mapValue will work.
545void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000546 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000547 LiveInterval::const_iterator B = parentli_.begin(), E = parentli_.end();
548 LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
549
550 // Check if --I begins before Start and overlaps.
551 if (I != B) {
552 --I;
553 if (I->end > Start)
554 addSimpleRange(Start, std::min(End, I->end), I->valno);
555 ++I;
556 }
557
558 // The remaining ranges begin after Start.
559 for (;I != E && I->start < End; ++I)
560 addSimpleRange(I->start, std::min(End, I->end), I->valno);
561}
562
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000563VNInfo *LiveIntervalMap::defByCopyFrom(unsigned Reg,
564 const VNInfo *ParentVNI,
565 MachineBasicBlock &MBB,
566 MachineBasicBlock::iterator I) {
567 const TargetInstrDesc &TID = MBB.getParent()->getTarget().getInstrInfo()->
568 get(TargetOpcode::COPY);
569 MachineInstr *MI = BuildMI(MBB, I, DebugLoc(), TID, li_->reg).addReg(Reg);
570 SlotIndex DefIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
571 VNInfo *VNI = defValue(ParentVNI, DefIdx);
572 VNI->setCopy(MI);
573 li_->addRange(LiveRange(DefIdx, DefIdx.getNextSlot(), VNI));
574 return VNI;
575}
576
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000577//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000578// Split Editor
579//===----------------------------------------------------------------------===//
580
581/// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000582SplitEditor::SplitEditor(SplitAnalysis &sa, LiveIntervals &lis, VirtRegMap &vrm,
Jakob Stoklund Olesen0a2b2a12010-08-13 22:56:53 +0000583 SmallVectorImpl<LiveInterval*> &intervals)
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000584 : sa_(sa), lis_(lis), vrm_(vrm),
585 mri_(vrm.getMachineFunction().getRegInfo()),
586 tii_(*vrm.getMachineFunction().getTarget().getInstrInfo()),
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000587 curli_(sa_.getCurLI()),
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000588 dupli_(lis_, *curli_),
589 openli_(lis_, *curli_),
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000590 intervals_(intervals),
591 firstInterval(intervals_.size())
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000592{
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000593 assert(curli_ && "SplitEditor created from empty SplitAnalysis");
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000594
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000595 // Make sure curli_ is assigned a stack slot, so all our intervals get the
596 // same slot as curli_.
597 if (vrm_.getStackSlot(curli_->reg) == VirtRegMap::NO_STACK_SLOT)
598 vrm_.assignVirt2StackSlot(curli_->reg);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000599
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000600}
601
602LiveInterval *SplitEditor::createInterval() {
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000603 unsigned Reg = mri_.createVirtualRegister(mri_.getRegClass(curli_->reg));
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000604 LiveInterval &Intv = lis_.getOrCreateInterval(Reg);
605 vrm_.grow();
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000606 vrm_.assignVirt2StackSlot(Reg, vrm_.getStackSlot(curli_->reg));
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000607 return &Intv;
608}
609
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000610bool SplitEditor::intervalsLiveAt(SlotIndex Idx) const {
611 for (int i = firstInterval, e = intervals_.size(); i != e; ++i)
612 if (intervals_[i]->liveAt(Idx))
613 return true;
614 return false;
615}
616
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000617/// Create a new virtual register and live interval.
618void SplitEditor::openIntv() {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000619 assert(!openli_.getLI() && "Previous LI not closed before openIntv");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000620
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000621 if (!dupli_.getLI())
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000622 dupli_.reset(createInterval());
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000623
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000624 openli_.reset(createInterval());
625 intervals_.push_back(openli_.getLI());
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000626}
627
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000628/// enterIntvBefore - Enter openli before the instruction at Idx. If curli is
629/// not live before Idx, a COPY is not inserted.
630void SplitEditor::enterIntvBefore(SlotIndex Idx) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000631 assert(openli_.getLI() && "openIntv not called before enterIntvBefore");
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000632 DEBUG(dbgs() << " enterIntvBefore " << Idx);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000633 VNInfo *ParentVNI = curli_->getVNInfoAt(Idx.getUseIndex());
634 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000635 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000636 return;
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000637 }
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000638 DEBUG(dbgs() << ": valno " << ParentVNI->id);
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000639 truncatedValues.insert(ParentVNI);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000640 MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
641 assert(MI && "enterIntvBefore called with invalid index");
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000642 VNInfo *VNI = openli_.defByCopyFrom(curli_->reg, ParentVNI,
643 *MI->getParent(), MI);
644 openli_.getLI()->addRange(LiveRange(VNI->def, Idx.getDefIndex(), VNI));
645 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000646}
647
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000648/// enterIntvAtEnd - Enter openli at the end of MBB.
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000649void SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000650 assert(openli_.getLI() && "openIntv not called before enterIntvAtEnd");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000651 SlotIndex End = lis_.getMBBEndIdx(&MBB);
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000652 DEBUG(dbgs() << " enterIntvAtEnd BB#" << MBB.getNumber() << ", " << End);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000653 VNInfo *ParentVNI = curli_->getVNInfoAt(End.getPrevSlot());
654 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000655 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000656 return;
657 }
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000658 DEBUG(dbgs() << ": valno " << ParentVNI->id);
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000659 truncatedValues.insert(ParentVNI);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000660 VNInfo *VNI = openli_.defByCopyFrom(curli_->reg, ParentVNI,
661 MBB, MBB.getFirstTerminator());
662 // Make sure openli is live out of MBB.
663 openli_.getLI()->addRange(LiveRange(VNI->def, End, VNI));
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000664 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000665}
666
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000667/// useIntv - indicate that all instructions in MBB should use openli.
668void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
669 useIntv(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB));
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000670}
671
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000672void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000673 assert(openli_.getLI() && "openIntv not called before useIntv");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000674 openli_.addRange(Start, End);
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000675 DEBUG(dbgs() << " use [" << Start << ';' << End << "): "
676 << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000677}
678
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000679/// leaveIntvAfter - Leave openli after the instruction at Idx.
680void SplitEditor::leaveIntvAfter(SlotIndex Idx) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000681 assert(openli_.getLI() && "openIntv not called before leaveIntvAfter");
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000682 DEBUG(dbgs() << " leaveIntvAfter " << Idx);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000683
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000684 // The interval must be live beyond the instruction at Idx.
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000685 VNInfo *ParentVNI = curli_->getVNInfoAt(Idx.getBoundaryIndex());
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000686 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000687 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000688 return;
689 }
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000690 DEBUG(dbgs() << ": valno " << ParentVNI->id);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000691
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000692 MachineBasicBlock::iterator MII = lis_.getInstructionFromIndex(Idx);
693 MachineBasicBlock *MBB = MII->getParent();
694 VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI, *MBB,
695 llvm::next(MII));
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000696
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000697 // Finally we must make sure that openli is properly extended from Idx to the
698 // new copy.
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000699 openli_.addSimpleRange(Idx.getBoundaryIndex(), VNI->def, ParentVNI);
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000700 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000701}
702
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000703/// leaveIntvAtTop - Leave the interval at the top of MBB.
704/// Currently, only one value can leave the interval.
705void SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000706 assert(openli_.getLI() && "openIntv not called before leaveIntvAtTop");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000707 SlotIndex Start = lis_.getMBBStartIdx(&MBB);
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000708 DEBUG(dbgs() << " leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000709
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000710 VNInfo *ParentVNI = curli_->getVNInfoAt(Start);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000711 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000712 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000713 return;
714 }
715
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000716 // We are going to insert a back copy, so we must have a dupli_.
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000717 VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI,
718 MBB, MBB.begin());
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000719
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000720 // Finally we must make sure that openli is properly extended from Start to
721 // the new copy.
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000722 openli_.addSimpleRange(Start, VNI->def, ParentVNI);
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000723 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000724}
725
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000726/// closeIntv - Indicate that we are done editing the currently open
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000727/// LiveInterval, and ranges can be trimmed.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000728void SplitEditor::closeIntv() {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000729 assert(openli_.getLI() && "openIntv not called before closeIntv");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000730
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000731 DEBUG(dbgs() << " closeIntv cleaning up\n");
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000732 DEBUG(dbgs() << " open " << *openli_.getLI() << '\n');
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000733 openli_.reset(0);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000734}
735
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000736/// rewrite - Rewrite all uses of reg to use the new registers.
737void SplitEditor::rewrite(unsigned reg) {
738 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(reg),
739 RE = mri_.reg_end(); RI != RE;) {
740 MachineOperand &MO = RI.getOperand();
741 MachineInstr *MI = MO.getParent();
742 ++RI;
743 if (MI->isDebugValue()) {
744 DEBUG(dbgs() << "Zapping " << *MI);
745 // FIXME: We can do much better with debug values.
746 MO.setReg(0);
747 continue;
748 }
749 SlotIndex Idx = lis_.getInstructionIndex(MI);
750 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
751 LiveInterval *LI = 0;
752 for (unsigned i = firstInterval, e = intervals_.size(); i != e; ++i) {
753 LiveInterval *testli = intervals_[i];
754 if (testli->liveAt(Idx)) {
755 LI = testli;
756 break;
757 }
758 }
759 assert(LI && "No register was live at use");
760 MO.setReg(LI->reg);
761 DEBUG(dbgs() << " rewrite BB#" << MI->getParent()->getNumber() << '\t'
762 << Idx << '\t' << *MI);
763 }
764}
765
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000766void
767SplitEditor::addTruncSimpleRange(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000768 // Build vector of iterator pairs from the intervals.
769 typedef std::pair<LiveInterval::const_iterator,
770 LiveInterval::const_iterator> IIPair;
771 SmallVector<IIPair, 8> Iters;
772 for (int i = firstInterval, e = intervals_.size(); i != e; ++i) {
773 LiveInterval::const_iterator I = intervals_[i]->find(Start);
774 LiveInterval::const_iterator E = intervals_[i]->end();
775 if (I != E)
776 Iters.push_back(std::make_pair(I, E));
777 }
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000778
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000779 SlotIndex sidx = Start;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000780 // Break [Start;End) into segments that don't overlap any intervals.
781 for (;;) {
782 SlotIndex next = sidx, eidx = End;
783 // Find overlapping intervals.
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000784 for (unsigned i = 0; i != Iters.size() && sidx < eidx; ++i) {
785 LiveInterval::const_iterator I = Iters[i].first;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000786 // Interval I is overlapping [sidx;eidx). Trim sidx.
787 if (I->start <= sidx) {
788 sidx = I->end;
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000789 // Move to the next run, remove iters when all are consumed.
790 I = ++Iters[i].first;
791 if (I == Iters[i].second) {
792 Iters.erase(Iters.begin() + i);
793 --i;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000794 continue;
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000795 }
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000796 }
797 // Trim eidx too if needed.
798 if (I->start >= eidx)
799 continue;
800 eidx = I->start;
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000801 next = I->end;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000802 }
803 // Now, [sidx;eidx) doesn't overlap anything in intervals_.
804 if (sidx < eidx)
805 dupli_.addSimpleRange(sidx, eidx, VNI);
806 // If the interval end was truncated, we can try again from next.
807 if (next <= sidx)
808 break;
809 sidx = next;
810 }
811}
812
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000813void SplitEditor::computeRemainder() {
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000814 // First we need to fill in the live ranges in dupli.
815 // If values were redefined, we need a full recoloring with SSA update.
816 // If values were truncated, we only need to truncate the ranges.
817 // If values were partially rematted, we should shrink to uses.
818 // If values were fully rematted, they should be omitted.
819 // FIXME: If a single value is redefined, just move the def and truncate.
820
821 // Values that are fully contained in the split intervals.
822 SmallPtrSet<const VNInfo*, 8> deadValues;
823
824 // Map all curli values that should have live defs in dupli.
825 for (LiveInterval::const_vni_iterator I = curli_->vni_begin(),
826 E = curli_->vni_end(); I != E; ++I) {
827 const VNInfo *VNI = *I;
828 // Original def is contained in the split intervals.
829 if (intervalsLiveAt(VNI->def)) {
830 // Did this value escape?
831 if (dupli_.isMapped(VNI))
832 truncatedValues.insert(VNI);
833 else
834 deadValues.insert(VNI);
835 continue;
836 }
837 // Add minimal live range at the definition.
838 VNInfo *DVNI = dupli_.defValue(VNI, VNI->def);
839 dupli_.getLI()->addRange(LiveRange(VNI->def, VNI->def.getNextSlot(), DVNI));
840 }
841
842 // Add all ranges to dupli.
843 for (LiveInterval::const_iterator I = curli_->begin(), E = curli_->end();
844 I != E; ++I) {
845 const LiveRange &LR = *I;
846 if (truncatedValues.count(LR.valno)) {
847 // recolor after removing intervals_.
848 addTruncSimpleRange(LR.start, LR.end, LR.valno);
849 } else if (!deadValues.count(LR.valno)) {
850 // recolor without truncation.
851 dupli_.addSimpleRange(LR.start, LR.end, LR.valno);
852 }
853 }
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000854}
855
856void SplitEditor::finish() {
857 assert(!openli_.getLI() && "Previous LI not closed before rewrite");
858 assert(dupli_.getLI() && "No dupli for rewrite. Noop spilt?");
859
860 // Complete dupli liveness.
861 computeRemainder();
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000862
Jakob Stoklund Olesen0253df92010-10-07 23:34:34 +0000863 // Get rid of unused values and set phi-kill flags.
864 dupli_.getLI()->RenumberValues(lis_);
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000865
Jakob Stoklund Olesen0253df92010-10-07 23:34:34 +0000866 // Now check if dupli was separated into multiple connected components.
867 ConnectedVNInfoEqClasses ConEQ(lis_);
868 if (unsigned NumComp = ConEQ.Classify(dupli_.getLI())) {
869 DEBUG(dbgs() << " Remainder has " << NumComp << " connected components: "
870 << *dupli_.getLI() << '\n');
871 unsigned firstComp = intervals_.size();
872 intervals_.push_back(dupli_.getLI());
873 // Did the remainder break up? Create intervals for all the components.
874 if (NumComp > 1) {
875 for (unsigned i = 1; i != NumComp; ++i)
876 intervals_.push_back(createInterval());
877 ConEQ.Distribute(&intervals_[firstComp]);
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000878 // Rewrite uses to the new regs.
879 rewrite(dupli_.getLI()->reg);
Jakob Stoklund Olesen0253df92010-10-07 23:34:34 +0000880 }
881 } else {
882 DEBUG(dbgs() << " dupli became empty?\n");
883 lis_.removeInterval(dupli_.getLI()->reg);
884 dupli_.reset(0);
885 }
886
887 // Rewrite instructions.
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000888 rewrite(curli_->reg);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000889
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +0000890 // Calculate spill weight and allocation hints for new intervals.
891 VirtRegAuxInfo vrai(vrm_.getMachineFunction(), lis_, sa_.loops_);
892 for (unsigned i = firstInterval, e = intervals_.size(); i != e; ++i) {
893 LiveInterval &li = *intervals_[i];
Jakob Stoklund Olesen9db3ea42010-08-10 18:37:40 +0000894 vrai.CalculateRegClass(li.reg);
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +0000895 vrai.CalculateWeightAndHint(li);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000896 DEBUG(dbgs() << " new interval " << mri_.getRegClass(li.reg)->getName()
897 << ":" << li << '\n');
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +0000898 }
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000899}
900
901
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000902//===----------------------------------------------------------------------===//
903// Loop Splitting
904//===----------------------------------------------------------------------===//
905
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +0000906void SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000907 SplitAnalysis::LoopBlocks Blocks;
908 sa_.getLoopBlocks(Loop, Blocks);
909
Jakob Stoklund Olesen452a9fd2010-10-07 18:47:07 +0000910 DEBUG({
911 dbgs() << " splitAroundLoop";
912 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
913 E = Blocks.Loop.end(); I != E; ++I)
914 dbgs() << " BB#" << (*I)->getNumber();
915 dbgs() << ", preds:";
916 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
917 E = Blocks.Preds.end(); I != E; ++I)
918 dbgs() << " BB#" << (*I)->getNumber();
919 dbgs() << ", exits:";
920 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
921 E = Blocks.Exits.end(); I != E; ++I)
922 dbgs() << " BB#" << (*I)->getNumber();
923 dbgs() << '\n';
924 });
925
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000926 // Break critical edges as needed.
927 SplitAnalysis::BlockPtrSet CriticalExits;
928 sa_.getCriticalExits(Blocks, CriticalExits);
929 assert(CriticalExits.empty() && "Cannot break critical exits yet");
930
931 // Create new live interval for the loop.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000932 openIntv();
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000933
934 // Insert copies in the predecessors.
935 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
936 E = Blocks.Preds.end(); I != E; ++I) {
937 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000938 enterIntvAtEnd(MBB);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000939 }
940
941 // Switch all loop blocks.
942 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
943 E = Blocks.Loop.end(); I != E; ++I)
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000944 useIntv(**I);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000945
946 // Insert back copies in the exit blocks.
947 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
948 E = Blocks.Exits.end(); I != E; ++I) {
949 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000950 leaveIntvAtTop(MBB);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000951 }
952
953 // Done.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000954 closeIntv();
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000955 finish();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000956}
957
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000958
959//===----------------------------------------------------------------------===//
960// Single Block Splitting
961//===----------------------------------------------------------------------===//
962
963/// splitSingleBlocks - Split curli into a separate live interval inside each
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +0000964/// basic block in Blocks.
965void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000966 DEBUG(dbgs() << " splitSingleBlocks for " << Blocks.size() << " blocks.\n");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000967 // Determine the first and last instruction using curli in each block.
968 typedef std::pair<SlotIndex,SlotIndex> IndexPair;
969 typedef DenseMap<const MachineBasicBlock*,IndexPair> IndexPairMap;
970 IndexPairMap MBBRange;
971 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
972 E = sa_.usingInstrs_.end(); I != E; ++I) {
973 const MachineBasicBlock *MBB = (*I)->getParent();
974 if (!Blocks.count(MBB))
975 continue;
976 SlotIndex Idx = lis_.getInstructionIndex(*I);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000977 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '\t' << Idx << '\t' << **I);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000978 IndexPair &IP = MBBRange[MBB];
979 if (!IP.first.isValid() || Idx < IP.first)
980 IP.first = Idx;
981 if (!IP.second.isValid() || Idx > IP.second)
982 IP.second = Idx;
983 }
984
985 // Create a new interval for each block.
986 for (SplitAnalysis::BlockPtrSet::const_iterator I = Blocks.begin(),
987 E = Blocks.end(); I != E; ++I) {
988 IndexPair &IP = MBBRange[*I];
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000989 DEBUG(dbgs() << " splitting for BB#" << (*I)->getNumber() << ": ["
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000990 << IP.first << ';' << IP.second << ")\n");
991 assert(IP.first.isValid() && IP.second.isValid());
992
993 openIntv();
994 enterIntvBefore(IP.first);
995 useIntv(IP.first.getBaseIndex(), IP.second.getBoundaryIndex());
996 leaveIntvAfter(IP.second);
997 closeIntv();
998 }
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000999 finish();
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001000}
1001
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001002
1003//===----------------------------------------------------------------------===//
1004// Sub Block Splitting
1005//===----------------------------------------------------------------------===//
1006
1007/// getBlockForInsideSplit - If curli is contained inside a single basic block,
1008/// and it wou pay to subdivide the interval inside that block, return it.
1009/// Otherwise return NULL. The returned block can be passed to
1010/// SplitEditor::splitInsideBlock.
1011const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
1012 // The interval must be exclusive to one block.
1013 if (usingBlocks_.size() != 1)
1014 return 0;
1015 // Don't to this for less than 4 instructions. We want to be sure that
1016 // splitting actually reduces the instruction count per interval.
1017 if (usingInstrs_.size() < 4)
1018 return 0;
1019 return usingBlocks_.begin()->first;
1020}
1021
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +00001022/// splitInsideBlock - Split curli into multiple intervals inside MBB.
1023void SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001024 SmallVector<SlotIndex, 32> Uses;
1025 Uses.reserve(sa_.usingInstrs_.size());
1026 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1027 E = sa_.usingInstrs_.end(); I != E; ++I)
1028 if ((*I)->getParent() == MBB)
1029 Uses.push_back(lis_.getInstructionIndex(*I));
1030 DEBUG(dbgs() << " splitInsideBlock BB#" << MBB->getNumber() << " for "
1031 << Uses.size() << " instructions.\n");
1032 assert(Uses.size() >= 3 && "Need at least 3 instructions");
1033 array_pod_sort(Uses.begin(), Uses.end());
1034
1035 // Simple algorithm: Find the largest gap between uses as determined by slot
1036 // indices. Create new intervals for instructions before the gap and after the
1037 // gap.
1038 unsigned bestPos = 0;
1039 int bestGap = 0;
1040 DEBUG(dbgs() << " dist (" << Uses[0]);
1041 for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
1042 int g = Uses[i-1].distance(Uses[i]);
1043 DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
1044 if (g > bestGap)
1045 bestPos = i, bestGap = g;
1046 }
1047 DEBUG(dbgs() << "), best: -" << bestGap << "-\n");
1048
1049 // bestPos points to the first use after the best gap.
1050 assert(bestPos > 0 && "Invalid gap");
1051
1052 // FIXME: Don't create intervals for low densities.
1053
1054 // First interval before the gap. Don't create single-instr intervals.
1055 if (bestPos > 1) {
1056 openIntv();
1057 enterIntvBefore(Uses.front());
1058 useIntv(Uses.front().getBaseIndex(), Uses[bestPos-1].getBoundaryIndex());
1059 leaveIntvAfter(Uses[bestPos-1]);
1060 closeIntv();
1061 }
1062
1063 // Second interval after the gap.
1064 if (bestPos < Uses.size()-1) {
1065 openIntv();
1066 enterIntvBefore(Uses[bestPos]);
1067 useIntv(Uses[bestPos].getBaseIndex(), Uses.back().getBoundaryIndex());
1068 leaveIntvAfter(Uses.back());
1069 closeIntv();
1070 }
1071
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +00001072 finish();
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001073}