blob: da85b428b52f535d82bac0fdaf2e89a89b76ac36 [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;
71 if (MachineLoop *Loop = loops_.getLoopFor(MBB))
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +000072 usingLoops_[Loop]++;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000073 }
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +000074 DEBUG(dbgs() << " counted "
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000075 << usingInstrs_.size() << " instrs, "
76 << usingBlocks_.size() << " blocks, "
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +000077 << usingLoops_.size() << " loops.\n");
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000078}
79
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +000080/// removeUse - Update statistics by noting that MI no longer uses curli.
81void SplitAnalysis::removeUse(const MachineInstr *MI) {
82 if (!usingInstrs_.erase(MI))
83 return;
84
85 // Decrement MBB count.
86 const MachineBasicBlock *MBB = MI->getParent();
87 BlockCountMap::iterator bi = usingBlocks_.find(MBB);
88 assert(bi != usingBlocks_.end() && "MBB missing");
89 assert(bi->second && "0 count in map");
90 if (--bi->second)
91 return;
92 // No more uses in MBB.
93 usingBlocks_.erase(bi);
94
95 // Decrement loop count.
96 MachineLoop *Loop = loops_.getLoopFor(MBB);
97 if (!Loop)
98 return;
99 LoopCountMap::iterator li = usingLoops_.find(Loop);
100 assert(li != usingLoops_.end() && "Loop missing");
101 assert(li->second && "0 count in map");
102 if (--li->second)
103 return;
104 // No more blocks in Loop.
105 usingLoops_.erase(li);
106}
107
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000108// Get three sets of basic blocks surrounding a loop: Blocks inside the loop,
109// predecessor blocks, and exit blocks.
110void SplitAnalysis::getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks) {
111 Blocks.clear();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000112
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000113 // Blocks in the loop.
114 Blocks.Loop.insert(Loop->block_begin(), Loop->block_end());
115
116 // Predecessor blocks.
117 const MachineBasicBlock *Header = Loop->getHeader();
118 for (MachineBasicBlock::const_pred_iterator I = Header->pred_begin(),
119 E = Header->pred_end(); I != E; ++I)
120 if (!Blocks.Loop.count(*I))
121 Blocks.Preds.insert(*I);
122
123 // Exit blocks.
124 for (MachineLoop::block_iterator I = Loop->block_begin(),
125 E = Loop->block_end(); I != E; ++I) {
126 const MachineBasicBlock *MBB = *I;
127 for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
128 SE = MBB->succ_end(); SI != SE; ++SI)
129 if (!Blocks.Loop.count(*SI))
130 Blocks.Exits.insert(*SI);
131 }
132}
133
134/// analyzeLoopPeripheralUse - Return an enum describing how curli_ is used in
135/// and around the Loop.
136SplitAnalysis::LoopPeripheralUse SplitAnalysis::
137analyzeLoopPeripheralUse(const SplitAnalysis::LoopBlocks &Blocks) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000138 LoopPeripheralUse use = ContainedInLoop;
139 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
140 I != E; ++I) {
141 const MachineBasicBlock *MBB = I->first;
142 // Is this a peripheral block?
143 if (use < MultiPeripheral &&
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000144 (Blocks.Preds.count(MBB) || Blocks.Exits.count(MBB))) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000145 if (I->second > 1) use = MultiPeripheral;
146 else use = SinglePeripheral;
147 continue;
148 }
149 // Is it a loop block?
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000150 if (Blocks.Loop.count(MBB))
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000151 continue;
152 // It must be an unrelated block.
153 return OutsideLoop;
154 }
155 return use;
156}
157
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000158/// getCriticalExits - It may be necessary to partially break critical edges
159/// leaving the loop if an exit block has phi uses of curli. Collect the exit
160/// blocks that need special treatment into CriticalExits.
161void SplitAnalysis::getCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
162 BlockPtrSet &CriticalExits) {
163 CriticalExits.clear();
164
165 // A critical exit block contains a phi def of curli, and has a predecessor
166 // that is not in the loop nor a loop predecessor.
167 // For such an exit block, the edges carrying the new variable must be moved
168 // to a new pre-exit block.
169 for (BlockPtrSet::iterator I = Blocks.Exits.begin(), E = Blocks.Exits.end();
170 I != E; ++I) {
171 const MachineBasicBlock *Succ = *I;
172 SlotIndex SuccIdx = lis_.getMBBStartIdx(Succ);
173 VNInfo *SuccVNI = curli_->getVNInfoAt(SuccIdx);
174 // This exit may not have curli live in at all. No need to split.
175 if (!SuccVNI)
176 continue;
177 // If this is not a PHI def, it is either using a value from before the
178 // loop, or a value defined inside the loop. Both are safe.
179 if (!SuccVNI->isPHIDef() || SuccVNI->def.getBaseIndex() != SuccIdx)
180 continue;
181 // This exit block does have a PHI. Does it also have a predecessor that is
182 // not a loop block or loop predecessor?
183 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
184 PE = Succ->pred_end(); PI != PE; ++PI) {
185 const MachineBasicBlock *Pred = *PI;
186 if (Blocks.Loop.count(Pred) || Blocks.Preds.count(Pred))
187 continue;
188 // This is a critical exit block, and we need to split the exit edge.
189 CriticalExits.insert(Succ);
190 break;
191 }
192 }
193}
194
195/// canSplitCriticalExits - Return true if it is possible to insert new exit
196/// blocks before the blocks in CriticalExits.
197bool
198SplitAnalysis::canSplitCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
199 BlockPtrSet &CriticalExits) {
200 // If we don't allow critical edge splitting, require no critical exits.
201 if (!AllowSplit)
202 return CriticalExits.empty();
203
204 for (BlockPtrSet::iterator I = CriticalExits.begin(), E = CriticalExits.end();
205 I != E; ++I) {
206 const MachineBasicBlock *Succ = *I;
207 // We want to insert a new pre-exit MBB before Succ, and change all the
208 // in-loop blocks to branch to the pre-exit instead of Succ.
209 // Check that all the in-loop predecessors can be changed.
210 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
211 PE = Succ->pred_end(); PI != PE; ++PI) {
212 const MachineBasicBlock *Pred = *PI;
213 // The external predecessors won't be altered.
214 if (!Blocks.Loop.count(Pred) && !Blocks.Preds.count(Pred))
215 continue;
216 if (!canAnalyzeBranch(Pred))
217 return false;
218 }
219
220 // If Succ's layout predecessor falls through, that too must be analyzable.
221 // We need to insert the pre-exit block in the gap.
222 MachineFunction::const_iterator MFI = Succ;
223 if (MFI == mf_.begin())
224 continue;
225 if (!canAnalyzeBranch(--MFI))
226 return false;
227 }
228 // No problems found.
229 return true;
230}
231
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000232void SplitAnalysis::analyze(const LiveInterval *li) {
233 clear();
234 curli_ = li;
Jakob Stoklund Olesenabff2802010-07-20 16:12:37 +0000235 analyzeUses();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000236}
237
238const MachineLoop *SplitAnalysis::getBestSplitLoop() {
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000239 assert(curli_ && "Call analyze() before getBestSplitLoop");
240 if (usingLoops_.empty())
241 return 0;
242
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000243 LoopPtrSet Loops, SecondLoops;
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000244 LoopBlocks Blocks;
245 BlockPtrSet CriticalExits;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000246
247 // Find first-class and second class candidate loops.
248 // We prefer to split around loops where curli is used outside the periphery.
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000249 for (LoopCountMap::const_iterator I = usingLoops_.begin(),
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000250 E = usingLoops_.end(); I != E; ++I) {
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000251 const MachineLoop *Loop = I->first;
252 getLoopBlocks(Loop, Blocks);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000253
254 // FIXME: We need an SSA updater to properly handle multiple exit blocks.
255 if (Blocks.Exits.size() > 1) {
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000256 DEBUG(dbgs() << " multiple exits from " << *Loop);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000257 continue;
258 }
259
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000260 LoopPtrSet *LPS = 0;
261 switch(analyzeLoopPeripheralUse(Blocks)) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000262 case OutsideLoop:
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000263 LPS = &Loops;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000264 break;
265 case MultiPeripheral:
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000266 LPS = &SecondLoops;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000267 break;
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000268 case ContainedInLoop:
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000269 DEBUG(dbgs() << " contained in " << *Loop);
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000270 continue;
271 case SinglePeripheral:
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000272 DEBUG(dbgs() << " single peripheral use in " << *Loop);
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000273 continue;
274 }
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000275 // Will it be possible to split around this loop?
276 getCriticalExits(Blocks, CriticalExits);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000277 DEBUG(dbgs() << " " << CriticalExits.size() << " critical exits from "
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000278 << *Loop);
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000279 if (!canSplitCriticalExits(Blocks, CriticalExits))
280 continue;
281 // This is a possible split.
282 assert(LPS);
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000283 LPS->insert(Loop);
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000284 }
285
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000286 DEBUG(dbgs() << " getBestSplitLoop found " << Loops.size() << " + "
287 << SecondLoops.size() << " candidate loops.\n");
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000288
289 // If there are no first class loops available, look at second class loops.
290 if (Loops.empty())
291 Loops = SecondLoops;
292
293 if (Loops.empty())
294 return 0;
295
296 // Pick the earliest loop.
297 // FIXME: Are there other heuristics to consider?
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000298 const MachineLoop *Best = 0;
299 SlotIndex BestIdx;
300 for (LoopPtrSet::const_iterator I = Loops.begin(), E = Loops.end(); I != E;
301 ++I) {
302 SlotIndex Idx = lis_.getMBBStartIdx((*I)->getHeader());
303 if (!Best || Idx < BestIdx)
304 Best = *I, BestIdx = Idx;
305 }
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000306 DEBUG(dbgs() << " getBestSplitLoop found " << *Best);
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000307 return Best;
308}
309
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000310/// getMultiUseBlocks - if curli has more than one use in a basic block, it
311/// may be an advantage to split curli for the duration of the block.
312bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
313 // If curli is local to one block, there is no point to splitting it.
314 if (usingBlocks_.size() <= 1)
315 return false;
316 // Add blocks with multiple uses.
317 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
318 I != E; ++I)
319 switch (I->second) {
320 case 0:
321 case 1:
322 continue;
323 case 2: {
324 // It doesn't pay to split a 2-instr block if it redefines curli.
325 VNInfo *VN1 = curli_->getVNInfoAt(lis_.getMBBStartIdx(I->first));
326 VNInfo *VN2 =
327 curli_->getVNInfoAt(lis_.getMBBEndIdx(I->first).getPrevIndex());
328 // live-in and live-out with a different value.
329 if (VN1 && VN2 && VN1 != VN2)
330 continue;
331 } // Fall through.
332 default:
333 Blocks.insert(I->first);
334 }
335 return !Blocks.empty();
336}
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000337
338//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000339// LiveIntervalMap
340//===----------------------------------------------------------------------===//
341
Jakob Stoklund Olesenb3e96812010-09-13 21:29:45 +0000342// Work around the fact that the std::pair constructors are broken for pointer
343// pairs in some implementations. makeVV(x, 0) works.
344static inline std::pair<const VNInfo*, VNInfo*>
345makeVV(const VNInfo *a, VNInfo *b) {
346 return std::make_pair(a, b);
347}
348
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000349void LiveIntervalMap::reset(LiveInterval *li) {
350 li_ = li;
351 valueMap_.clear();
352}
353
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000354bool LiveIntervalMap::isComplexMapped(const VNInfo *ParentVNI) const {
355 ValueMap::const_iterator i = valueMap_.find(ParentVNI);
356 return i != valueMap_.end() && i->second == 0;
357}
358
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000359// defValue - Introduce a li_ def for ParentVNI that could be later than
360// ParentVNI->def.
361VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000362 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000363 assert(ParentVNI && "Mapping NULL value");
364 assert(Idx.isValid() && "Invalid SlotIndex");
365 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
366
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000367 // Create a new value.
368 VNInfo *VNI = li_->getNextValue(Idx, 0, true, lis_.getVNInfoAllocator());
369
370 // Use insert for lookup, so we can add missing values with a second lookup.
371 std::pair<ValueMap::iterator,bool> InsP =
372 valueMap_.insert(makeVV(ParentVNI, Idx == ParentVNI->def ? VNI : 0));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000373
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000374 // This is now a complex def. Mark with a NULL in valueMap.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000375 if (!InsP.second)
376 InsP.first->second = 0;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000377
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000378 return VNI;
379}
380
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000381
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000382// mapValue - Find the mapped value for ParentVNI at Idx.
383// Potentially create phi-def values.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000384VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx,
385 bool *simple) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000386 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000387 assert(ParentVNI && "Mapping NULL value");
388 assert(Idx.isValid() && "Invalid SlotIndex");
389 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
390
391 // Use insert for lookup, so we can add missing values with a second lookup.
392 std::pair<ValueMap::iterator,bool> InsP =
Jakob Stoklund Olesenb3e96812010-09-13 21:29:45 +0000393 valueMap_.insert(makeVV(ParentVNI, 0));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000394
395 // This was an unknown value. Create a simple mapping.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000396 if (InsP.second) {
397 if (simple) *simple = true;
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000398 return InsP.first->second = li_->createValueCopy(ParentVNI,
399 lis_.getVNInfoAllocator());
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000400 }
401
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000402 // This was a simple mapped value.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000403 if (InsP.first->second) {
404 if (simple) *simple = true;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000405 return InsP.first->second;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000406 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000407
408 // This is a complex mapped value. There may be multiple defs, and we may need
409 // to create phi-defs.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000410 if (simple) *simple = false;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000411 MachineBasicBlock *IdxMBB = lis_.getMBBFromIndex(Idx);
412 assert(IdxMBB && "No MBB at Idx");
413
414 // Is there a def in the same MBB we can extend?
415 if (VNInfo *VNI = extendTo(IdxMBB, Idx))
416 return VNI;
417
418 // Now for the fun part. We know that ParentVNI potentially has multiple defs,
419 // and we may need to create even more phi-defs to preserve VNInfo SSA form.
420 // Perform a depth-first search for predecessor blocks where we know the
421 // dominating VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
422
423 // Track MBBs where we have created or learned the dominating value.
424 // This may change during the DFS as we create new phi-defs.
425 typedef DenseMap<MachineBasicBlock*, VNInfo*> MBBValueMap;
426 MBBValueMap DomValue;
427
428 for (idf_iterator<MachineBasicBlock*>
429 IDFI = idf_begin(IdxMBB),
430 IDFE = idf_end(IdxMBB); IDFI != IDFE;) {
431 MachineBasicBlock *MBB = *IDFI;
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000432 SlotIndex End = lis_.getMBBEndIdx(MBB).getPrevSlot();
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000433
434 // We are operating on the restricted CFG where ParentVNI is live.
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000435 if (parentli_.getVNInfoAt(End) != ParentVNI) {
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000436 IDFI.skipChildren();
437 continue;
438 }
439
440 // Do we have a dominating value in this block?
441 VNInfo *VNI = extendTo(MBB, End);
442 if (!VNI) {
443 ++IDFI;
444 continue;
445 }
446
447 // Yes, VNI dominates MBB. Track the path back to IdxMBB, creating phi-defs
448 // as needed along the way.
449 for (unsigned PI = IDFI.getPathLength()-1; PI != 0; --PI) {
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000450 // Start from MBB's immediate successor. End at IdxMBB.
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000451 MachineBasicBlock *Succ = IDFI.getPath(PI-1);
452 std::pair<MBBValueMap::iterator, bool> InsP =
453 DomValue.insert(MBBValueMap::value_type(Succ, VNI));
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000454
455 // This is the first time we backtrack to Succ.
456 if (InsP.second)
457 continue;
458
459 // We reached Succ again with the same VNI. Nothing is going to change.
460 VNInfo *OVNI = InsP.first->second;
461 if (OVNI == VNI)
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000462 break;
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000463
464 // Succ already has a phi-def. No need to continue.
465 SlotIndex Start = lis_.getMBBStartIdx(Succ);
466 if (OVNI->def == Start)
467 break;
468
469 // We have a collision between the old and new VNI at Succ. That means
470 // neither dominates and we need a new phi-def.
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000471 VNI = li_->getNextValue(Start, 0, true, lis_.getVNInfoAllocator());
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000472 VNI->setIsPHIDef(true);
473 InsP.first->second = VNI;
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000474
475 // Replace OVNI with VNI in the remaining path.
476 for (; PI > 1 ; --PI) {
477 MBBValueMap::iterator I = DomValue.find(IDFI.getPath(PI-2));
478 if (I == DomValue.end() || I->second != OVNI)
479 break;
480 I->second = VNI;
481 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000482 }
483
484 // No need to search the children, we found a dominating value.
Jakob Stoklund Olesencf16bea2010-08-18 20:06:05 +0000485 IDFI.skipChildren();
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000486 }
487
488 // The search should at least find a dominating value for IdxMBB.
489 assert(!DomValue.empty() && "Couldn't find a reaching definition");
490
491 // Since we went through the trouble of a full DFS visiting all reaching defs,
492 // the values in DomValue are now accurate. No more phi-defs are needed for
493 // these blocks, so we can color the live ranges.
494 // This makes the next mapValue call much faster.
495 VNInfo *IdxVNI = 0;
496 for (MBBValueMap::iterator I = DomValue.begin(), E = DomValue.end(); I != E;
497 ++I) {
498 MachineBasicBlock *MBB = I->first;
499 VNInfo *VNI = I->second;
500 SlotIndex Start = lis_.getMBBStartIdx(MBB);
501 if (MBB == IdxMBB) {
502 // Don't add full liveness to IdxMBB, stop at Idx.
503 if (Start != Idx)
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000504 li_->addRange(LiveRange(Start, Idx.getNextSlot(), VNI));
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000505 // The caller had better add some liveness to IdxVNI, or it leaks.
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000506 IdxVNI = VNI;
507 } else
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000508 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000509 }
510
511 assert(IdxVNI && "Didn't find value for Idx");
512 return IdxVNI;
513}
514
515// extendTo - Find the last li_ value defined in MBB at or before Idx. The
516// parentli_ is assumed to be live at Idx. Extend the live range to Idx.
517// Return the found VNInfo, or NULL.
518VNInfo *LiveIntervalMap::extendTo(MachineBasicBlock *MBB, SlotIndex Idx) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000519 assert(li_ && "call reset first");
520 LiveInterval::iterator I = std::upper_bound(li_->begin(), li_->end(), Idx);
521 if (I == li_->begin())
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000522 return 0;
523 --I;
524 if (I->start < lis_.getMBBStartIdx(MBB))
525 return 0;
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000526 if (I->end <= Idx)
527 I->end = Idx.getNextSlot();
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000528 return I->valno;
529}
530
531// addSimpleRange - Add a simple range from parentli_ to li_.
532// ParentVNI must be live in the [Start;End) interval.
533void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End,
534 const VNInfo *ParentVNI) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000535 assert(li_ && "call reset first");
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000536 bool simple;
537 VNInfo *VNI = mapValue(ParentVNI, Start, &simple);
538 // A simple mapping is easy.
539 if (simple) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000540 li_->addRange(LiveRange(Start, End, VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000541 return;
542 }
543
544 // ParentVNI is a complex value. We must map per MBB.
545 MachineFunction::iterator MBB = lis_.getMBBFromIndex(Start);
546 MachineFunction::iterator MBBE = lis_.getMBBFromIndex(End);
547
548 if (MBB == MBBE) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000549 li_->addRange(LiveRange(Start, End, VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000550 return;
551 }
552
553 // First block.
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000554 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000555
556 // Run sequence of full blocks.
557 for (++MBB; MBB != MBBE; ++MBB) {
558 Start = lis_.getMBBStartIdx(MBB);
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000559 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB),
560 mapValue(ParentVNI, Start)));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000561 }
562
563 // Final block.
564 Start = lis_.getMBBStartIdx(MBB);
565 if (Start != End)
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000566 li_->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start)));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000567}
568
569/// addRange - Add live ranges to li_ where [Start;End) intersects parentli_.
570/// All needed values whose def is not inside [Start;End) must be defined
571/// beforehand so mapValue will work.
572void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000573 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000574 LiveInterval::const_iterator B = parentli_.begin(), E = parentli_.end();
575 LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
576
577 // Check if --I begins before Start and overlaps.
578 if (I != B) {
579 --I;
580 if (I->end > Start)
581 addSimpleRange(Start, std::min(End, I->end), I->valno);
582 ++I;
583 }
584
585 // The remaining ranges begin after Start.
586 for (;I != E && I->start < End; ++I)
587 addSimpleRange(I->start, std::min(End, I->end), I->valno);
588}
589
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000590VNInfo *LiveIntervalMap::defByCopyFrom(unsigned Reg,
591 const VNInfo *ParentVNI,
592 MachineBasicBlock &MBB,
593 MachineBasicBlock::iterator I) {
594 const TargetInstrDesc &TID = MBB.getParent()->getTarget().getInstrInfo()->
595 get(TargetOpcode::COPY);
596 MachineInstr *MI = BuildMI(MBB, I, DebugLoc(), TID, li_->reg).addReg(Reg);
597 SlotIndex DefIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
598 VNInfo *VNI = defValue(ParentVNI, DefIdx);
599 VNI->setCopy(MI);
600 li_->addRange(LiveRange(DefIdx, DefIdx.getNextSlot(), VNI));
601 return VNI;
602}
603
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000604//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000605// Split Editor
606//===----------------------------------------------------------------------===//
607
608/// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000609SplitEditor::SplitEditor(SplitAnalysis &sa, LiveIntervals &lis, VirtRegMap &vrm,
Jakob Stoklund Olesen0a2b2a12010-08-13 22:56:53 +0000610 SmallVectorImpl<LiveInterval*> &intervals)
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000611 : sa_(sa), lis_(lis), vrm_(vrm),
612 mri_(vrm.getMachineFunction().getRegInfo()),
613 tii_(*vrm.getMachineFunction().getTarget().getInstrInfo()),
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000614 curli_(sa_.getCurLI()),
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000615 dupli_(lis_, *curli_),
616 openli_(lis_, *curli_),
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000617 intervals_(intervals),
618 firstInterval(intervals_.size())
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000619{
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000620 assert(curli_ && "SplitEditor created from empty SplitAnalysis");
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000621
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000622 // Make sure curli_ is assigned a stack slot, so all our intervals get the
623 // same slot as curli_.
624 if (vrm_.getStackSlot(curli_->reg) == VirtRegMap::NO_STACK_SLOT)
625 vrm_.assignVirt2StackSlot(curli_->reg);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000626
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000627}
628
629LiveInterval *SplitEditor::createInterval() {
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000630 unsigned Reg = mri_.createVirtualRegister(mri_.getRegClass(curli_->reg));
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000631 LiveInterval &Intv = lis_.getOrCreateInterval(Reg);
632 vrm_.grow();
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000633 vrm_.assignVirt2StackSlot(Reg, vrm_.getStackSlot(curli_->reg));
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000634 return &Intv;
635}
636
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000637bool SplitEditor::intervalsLiveAt(SlotIndex Idx) const {
638 for (int i = firstInterval, e = intervals_.size(); i != e; ++i)
639 if (intervals_[i]->liveAt(Idx))
640 return true;
641 return false;
642}
643
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000644/// Create a new virtual register and live interval.
645void SplitEditor::openIntv() {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000646 assert(!openli_.getLI() && "Previous LI not closed before openIntv");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000647
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000648 if (!dupli_.getLI())
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000649 dupli_.reset(createInterval());
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000650
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000651 openli_.reset(createInterval());
652 intervals_.push_back(openli_.getLI());
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000653}
654
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000655/// enterIntvBefore - Enter openli before the instruction at Idx. If curli is
656/// not live before Idx, a COPY is not inserted.
657void SplitEditor::enterIntvBefore(SlotIndex Idx) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000658 assert(openli_.getLI() && "openIntv not called before enterIntvBefore");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000659 VNInfo *ParentVNI = curli_->getVNInfoAt(Idx.getUseIndex());
660 if (!ParentVNI) {
661 DEBUG(dbgs() << " enterIntvBefore " << Idx << ": not live\n");
662 return;
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000663 }
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000664 truncatedValues.insert(ParentVNI);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000665 MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
666 assert(MI && "enterIntvBefore called with invalid index");
667 openli_.defByCopyFrom(curli_->reg, ParentVNI, *MI->getParent(), MI);
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000668 DEBUG(dbgs() << " enterIntvBefore " << Idx << ": " << *openli_.getLI()
669 << '\n');
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000670}
671
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000672/// enterIntvAtEnd - Enter openli at the end of MBB.
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000673void SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000674 assert(openli_.getLI() && "openIntv not called before enterIntvAtEnd");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000675 SlotIndex End = lis_.getMBBEndIdx(&MBB);
676 VNInfo *ParentVNI = curli_->getVNInfoAt(End.getPrevSlot());
677 if (!ParentVNI) {
678 DEBUG(dbgs() << " enterIntvAtEnd " << End << ": not live\n");
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000679 return;
680 }
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000681 truncatedValues.insert(ParentVNI);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000682 VNInfo *VNI = openli_.defByCopyFrom(curli_->reg, ParentVNI,
683 MBB, MBB.getFirstTerminator());
684 // Make sure openli is live out of MBB.
685 openli_.getLI()->addRange(LiveRange(VNI->def, End, VNI));
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000686 DEBUG(dbgs() << " enterIntvAtEnd: " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000687}
688
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000689/// useIntv - indicate that all instructions in MBB should use openli.
690void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
691 useIntv(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB));
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000692}
693
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000694void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000695 assert(openli_.getLI() && "openIntv not called before useIntv");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000696 openli_.addRange(Start, End);
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000697 DEBUG(dbgs() << " use [" << Start << ';' << End << "): "
698 << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000699}
700
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000701/// leaveIntvAfter - Leave openli after the instruction at Idx.
702void SplitEditor::leaveIntvAfter(SlotIndex Idx) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000703 assert(openli_.getLI() && "openIntv not called before leaveIntvAfter");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000704
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000705 // The interval must be live beyond the instruction at Idx.
706 SlotIndex EndIdx = Idx.getNextIndex().getBaseIndex();
707 VNInfo *ParentVNI = curli_->getVNInfoAt(EndIdx);
708 if (!ParentVNI) {
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000709 DEBUG(dbgs() << " leaveIntvAfter " << Idx << ": not live\n");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000710 return;
711 }
712
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000713 MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
714 assert(MI && "leaveIntvAfter called with invalid index");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000715
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000716 VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI,
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000717 *MI->getParent(), MI);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000718
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000719 // Finally we must make sure that openli is properly extended from Idx to the
720 // new copy.
721 openli_.mapValue(ParentVNI, VNI->def.getUseIndex());
722
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000723 DEBUG(dbgs() << " leaveIntvAfter " << Idx << ": " << *openli_.getLI()
724 << '\n');
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000725}
726
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000727/// leaveIntvAtTop - Leave the interval at the top of MBB.
728/// Currently, only one value can leave the interval.
729void SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000730 assert(openli_.getLI() && "openIntv not called before leaveIntvAtTop");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000731
732 SlotIndex Start = lis_.getMBBStartIdx(&MBB);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000733 VNInfo *ParentVNI = curli_->getVNInfoAt(Start);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000734
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000735 // Is curli even live-in to MBB?
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000736 if (!ParentVNI) {
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000737 DEBUG(dbgs() << " leaveIntvAtTop at " << Start << ": not live\n");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000738 return;
739 }
740
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000741 // We are going to insert a back copy, so we must have a dupli_.
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000742 VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI,
743 MBB, MBB.begin());
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000744
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000745 // Finally we must make sure that openli is properly extended from Start to
746 // the new copy.
747 openli_.mapValue(ParentVNI, VNI->def.getUseIndex());
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000748
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000749 DEBUG(dbgs() << " leaveIntvAtTop at " << Start << ": " << *openli_.getLI()
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000750 << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000751}
752
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000753/// closeIntv - Indicate that we are done editing the currently open
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000754/// LiveInterval, and ranges can be trimmed.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000755void SplitEditor::closeIntv() {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000756 assert(openli_.getLI() && "openIntv not called before closeIntv");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000757
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000758 DEBUG(dbgs() << " closeIntv cleaning up\n");
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000759 DEBUG(dbgs() << " open " << *openli_.getLI() << '\n');
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000760 openli_.reset(0);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000761}
762
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000763void
764SplitEditor::addTruncSimpleRange(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
765 SlotIndex sidx = Start;
766
767 // Break [Start;End) into segments that don't overlap any intervals.
768 for (;;) {
769 SlotIndex next = sidx, eidx = End;
770 // Find overlapping intervals.
771 for (int i = firstInterval, e = intervals_.size(); i != e && sidx < eidx;
772 ++i) {
773 LiveInterval::const_iterator I = intervals_[i]->find(sidx);
774 LiveInterval::const_iterator E = intervals_[i]->end();
775 if (I == E)
776 continue;
777 // Interval I is overlapping [sidx;eidx). Trim sidx.
778 if (I->start <= sidx) {
779 sidx = I->end;
780 if (++I == E)
781 continue;
782 }
783 // Trim eidx too if needed.
784 if (I->start >= eidx)
785 continue;
786 eidx = I->start;
787 if (I->end > next)
788 next = I->end;
789 }
790 // Now, [sidx;eidx) doesn't overlap anything in intervals_.
791 if (sidx < eidx)
792 dupli_.addSimpleRange(sidx, eidx, VNI);
793 // If the interval end was truncated, we can try again from next.
794 if (next <= sidx)
795 break;
796 sidx = next;
797 }
798}
799
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000800/// rewrite - after all the new live ranges have been created, rewrite
801/// instructions using curli to use the new intervals.
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000802bool SplitEditor::rewrite() {
803 assert(!openli_.getLI() && "Previous LI not closed before rewrite");
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000804
805 // First we need to fill in the live ranges in dupli.
806 // If values were redefined, we need a full recoloring with SSA update.
807 // If values were truncated, we only need to truncate the ranges.
808 // If values were partially rematted, we should shrink to uses.
809 // If values were fully rematted, they should be omitted.
810 // FIXME: If a single value is redefined, just move the def and truncate.
811
812 // Values that are fully contained in the split intervals.
813 SmallPtrSet<const VNInfo*, 8> deadValues;
814
815 // Map all curli values that should have live defs in dupli.
816 for (LiveInterval::const_vni_iterator I = curli_->vni_begin(),
817 E = curli_->vni_end(); I != E; ++I) {
818 const VNInfo *VNI = *I;
819 // Original def is contained in the split intervals.
820 if (intervalsLiveAt(VNI->def)) {
821 // Did this value escape?
822 if (dupli_.isMapped(VNI))
823 truncatedValues.insert(VNI);
824 else
825 deadValues.insert(VNI);
826 continue;
827 }
828 // Add minimal live range at the definition.
829 VNInfo *DVNI = dupli_.defValue(VNI, VNI->def);
830 dupli_.getLI()->addRange(LiveRange(VNI->def, VNI->def.getNextSlot(), DVNI));
831 }
832
833 // Add all ranges to dupli.
834 for (LiveInterval::const_iterator I = curli_->begin(), E = curli_->end();
835 I != E; ++I) {
836 const LiveRange &LR = *I;
837 if (truncatedValues.count(LR.valno)) {
838 // recolor after removing intervals_.
839 addTruncSimpleRange(LR.start, LR.end, LR.valno);
840 } else if (!deadValues.count(LR.valno)) {
841 // recolor without truncation.
842 dupli_.addSimpleRange(LR.start, LR.end, LR.valno);
843 }
844 }
845
846
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000847 const LiveInterval *curli = sa_.getCurLI();
848 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(curli->reg),
849 RE = mri_.reg_end(); RI != RE;) {
850 MachineOperand &MO = RI.getOperand();
851 MachineInstr *MI = MO.getParent();
852 ++RI;
853 if (MI->isDebugValue()) {
854 DEBUG(dbgs() << "Zapping " << *MI);
855 // FIXME: We can do much better with debug values.
856 MO.setReg(0);
857 continue;
858 }
859 SlotIndex Idx = lis_.getInstructionIndex(MI);
860 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000861 LiveInterval *LI = dupli_.getLI();
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000862 for (unsigned i = firstInterval, e = intervals_.size(); i != e; ++i) {
863 LiveInterval *testli = intervals_[i];
864 if (testli->liveAt(Idx)) {
865 LI = testli;
866 break;
867 }
868 }
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000869 if (LI) {
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000870 MO.setReg(LI->reg);
Jakob Stoklund Olesen00667a52010-08-13 01:05:23 +0000871 sa_.removeUse(MI);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000872 DEBUG(dbgs() << " rewrite " << Idx << '\t' << *MI);
873 }
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000874 }
875
876 // dupli_ goes in last, after rewriting.
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000877 if (dupli_.getLI()) {
878 if (dupli_.getLI()->empty()) {
Jakob Stoklund Olesen09c45d22010-08-12 23:02:57 +0000879 DEBUG(dbgs() << " dupli became empty?\n");
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000880 lis_.removeInterval(dupli_.getLI()->reg);
881 dupli_.reset(0);
Jakob Stoklund Olesen09c45d22010-08-12 23:02:57 +0000882 } else {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000883 dupli_.getLI()->RenumberValues(lis_);
884 intervals_.push_back(dupli_.getLI());
Jakob Stoklund Olesen09c45d22010-08-12 23:02:57 +0000885 }
Jakob Stoklund Olesen23436592010-08-06 18:46:59 +0000886 }
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000887
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +0000888 // Calculate spill weight and allocation hints for new intervals.
889 VirtRegAuxInfo vrai(vrm_.getMachineFunction(), lis_, sa_.loops_);
890 for (unsigned i = firstInterval, e = intervals_.size(); i != e; ++i) {
891 LiveInterval &li = *intervals_[i];
Jakob Stoklund Olesen9db3ea42010-08-10 18:37:40 +0000892 vrai.CalculateRegClass(li.reg);
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +0000893 vrai.CalculateWeightAndHint(li);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000894 DEBUG(dbgs() << " new interval " << mri_.getRegClass(li.reg)->getName()
895 << ":" << li << '\n');
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +0000896 }
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000897 return dupli_.getLI();
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000898}
899
900
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000901//===----------------------------------------------------------------------===//
902// Loop Splitting
903//===----------------------------------------------------------------------===//
904
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000905bool SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000906 SplitAnalysis::LoopBlocks Blocks;
907 sa_.getLoopBlocks(Loop, Blocks);
908
909 // Break critical edges as needed.
910 SplitAnalysis::BlockPtrSet CriticalExits;
911 sa_.getCriticalExits(Blocks, CriticalExits);
912 assert(CriticalExits.empty() && "Cannot break critical exits yet");
913
914 // Create new live interval for the loop.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000915 openIntv();
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000916
917 // Insert copies in the predecessors.
918 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
919 E = Blocks.Preds.end(); I != E; ++I) {
920 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000921 enterIntvAtEnd(MBB);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000922 }
923
924 // Switch all loop blocks.
925 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
926 E = Blocks.Loop.end(); I != E; ++I)
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000927 useIntv(**I);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000928
929 // Insert back copies in the exit blocks.
930 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
931 E = Blocks.Exits.end(); I != E; ++I) {
932 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000933 leaveIntvAtTop(MBB);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000934 }
935
936 // Done.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000937 closeIntv();
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000938 return rewrite();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000939}
940
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000941
942//===----------------------------------------------------------------------===//
943// Single Block Splitting
944//===----------------------------------------------------------------------===//
945
946/// splitSingleBlocks - Split curli into a separate live interval inside each
947/// basic block in Blocks. Return true if curli has been completely replaced,
948/// false if curli is still intact, and needs to be spilled or split further.
949bool SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000950 DEBUG(dbgs() << " splitSingleBlocks for " << Blocks.size() << " blocks.\n");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000951 // Determine the first and last instruction using curli in each block.
952 typedef std::pair<SlotIndex,SlotIndex> IndexPair;
953 typedef DenseMap<const MachineBasicBlock*,IndexPair> IndexPairMap;
954 IndexPairMap MBBRange;
955 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
956 E = sa_.usingInstrs_.end(); I != E; ++I) {
957 const MachineBasicBlock *MBB = (*I)->getParent();
958 if (!Blocks.count(MBB))
959 continue;
960 SlotIndex Idx = lis_.getInstructionIndex(*I);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000961 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '\t' << Idx << '\t' << **I);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000962 IndexPair &IP = MBBRange[MBB];
963 if (!IP.first.isValid() || Idx < IP.first)
964 IP.first = Idx;
965 if (!IP.second.isValid() || Idx > IP.second)
966 IP.second = Idx;
967 }
968
969 // Create a new interval for each block.
970 for (SplitAnalysis::BlockPtrSet::const_iterator I = Blocks.begin(),
971 E = Blocks.end(); I != E; ++I) {
972 IndexPair &IP = MBBRange[*I];
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000973 DEBUG(dbgs() << " splitting for BB#" << (*I)->getNumber() << ": ["
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000974 << IP.first << ';' << IP.second << ")\n");
975 assert(IP.first.isValid() && IP.second.isValid());
976
977 openIntv();
978 enterIntvBefore(IP.first);
979 useIntv(IP.first.getBaseIndex(), IP.second.getBoundaryIndex());
980 leaveIntvAfter(IP.second);
981 closeIntv();
982 }
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000983 return rewrite();
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000984}
985
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +0000986
987//===----------------------------------------------------------------------===//
988// Sub Block Splitting
989//===----------------------------------------------------------------------===//
990
991/// getBlockForInsideSplit - If curli is contained inside a single basic block,
992/// and it wou pay to subdivide the interval inside that block, return it.
993/// Otherwise return NULL. The returned block can be passed to
994/// SplitEditor::splitInsideBlock.
995const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
996 // The interval must be exclusive to one block.
997 if (usingBlocks_.size() != 1)
998 return 0;
999 // Don't to this for less than 4 instructions. We want to be sure that
1000 // splitting actually reduces the instruction count per interval.
1001 if (usingInstrs_.size() < 4)
1002 return 0;
1003 return usingBlocks_.begin()->first;
1004}
1005
1006/// splitInsideBlock - Split curli into multiple intervals inside MBB. Return
1007/// true if curli has been completely replaced, false if curli is still
1008/// intact, and needs to be spilled or split further.
1009bool SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
1010 SmallVector<SlotIndex, 32> Uses;
1011 Uses.reserve(sa_.usingInstrs_.size());
1012 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1013 E = sa_.usingInstrs_.end(); I != E; ++I)
1014 if ((*I)->getParent() == MBB)
1015 Uses.push_back(lis_.getInstructionIndex(*I));
1016 DEBUG(dbgs() << " splitInsideBlock BB#" << MBB->getNumber() << " for "
1017 << Uses.size() << " instructions.\n");
1018 assert(Uses.size() >= 3 && "Need at least 3 instructions");
1019 array_pod_sort(Uses.begin(), Uses.end());
1020
1021 // Simple algorithm: Find the largest gap between uses as determined by slot
1022 // indices. Create new intervals for instructions before the gap and after the
1023 // gap.
1024 unsigned bestPos = 0;
1025 int bestGap = 0;
1026 DEBUG(dbgs() << " dist (" << Uses[0]);
1027 for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
1028 int g = Uses[i-1].distance(Uses[i]);
1029 DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
1030 if (g > bestGap)
1031 bestPos = i, bestGap = g;
1032 }
1033 DEBUG(dbgs() << "), best: -" << bestGap << "-\n");
1034
1035 // bestPos points to the first use after the best gap.
1036 assert(bestPos > 0 && "Invalid gap");
1037
1038 // FIXME: Don't create intervals for low densities.
1039
1040 // First interval before the gap. Don't create single-instr intervals.
1041 if (bestPos > 1) {
1042 openIntv();
1043 enterIntvBefore(Uses.front());
1044 useIntv(Uses.front().getBaseIndex(), Uses[bestPos-1].getBoundaryIndex());
1045 leaveIntvAfter(Uses[bestPos-1]);
1046 closeIntv();
1047 }
1048
1049 // Second interval after the gap.
1050 if (bestPos < Uses.size()-1) {
1051 openIntv();
1052 enterIntvBefore(Uses[bestPos]);
1053 useIntv(Uses[bestPos].getBaseIndex(), Uses.back().getBoundaryIndex());
1054 leaveIntvAfter(Uses.back());
1055 closeIntv();
1056 }
1057
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +00001058 return rewrite();
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001059}