blob: 5b9f49d11a9497d23bc70d7af586f19be4cf3d6d [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 Olesen1407c842010-08-18 19:00:08 +0000354// defValue - Introduce a li_ def for ParentVNI that could be later than
355// ParentVNI->def.
356VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000357 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000358 assert(ParentVNI && "Mapping NULL value");
359 assert(Idx.isValid() && "Invalid SlotIndex");
360 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
361
362 // Is this a simple 1-1 mapping? Not likely.
363 if (Idx == ParentVNI->def)
364 return mapValue(ParentVNI, Idx);
365
366 // This is a complex def. Mark with a NULL in valueMap.
Jakob Stoklund Olesenb3e96812010-09-13 21:29:45 +0000367 VNInfo *&OldVNI = valueMap_[ParentVNI];
368 assert(!OldVNI && "Simple/Complex values mixed");
369 OldVNI = 0;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000370
371 // Should we insert a minimal snippet of VNI LiveRange, or can we count on
372 // callers to do that? We need it for lookups of complex values.
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000373 VNInfo *VNI = li_->getNextValue(Idx, 0, true, lis_.getVNInfoAllocator());
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000374 return VNI;
375}
376
377// mapValue - Find the mapped value for ParentVNI at Idx.
378// Potentially create phi-def values.
379VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000380 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000381 assert(ParentVNI && "Mapping NULL value");
382 assert(Idx.isValid() && "Invalid SlotIndex");
383 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
384
385 // Use insert for lookup, so we can add missing values with a second lookup.
386 std::pair<ValueMap::iterator,bool> InsP =
Jakob Stoklund Olesenb3e96812010-09-13 21:29:45 +0000387 valueMap_.insert(makeVV(ParentVNI, 0));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000388
389 // This was an unknown value. Create a simple mapping.
390 if (InsP.second)
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000391 return InsP.first->second = li_->createValueCopy(ParentVNI,
392 lis_.getVNInfoAllocator());
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000393 // This was a simple mapped value.
394 if (InsP.first->second)
395 return InsP.first->second;
396
397 // This is a complex mapped value. There may be multiple defs, and we may need
398 // to create phi-defs.
399 MachineBasicBlock *IdxMBB = lis_.getMBBFromIndex(Idx);
400 assert(IdxMBB && "No MBB at Idx");
401
402 // Is there a def in the same MBB we can extend?
403 if (VNInfo *VNI = extendTo(IdxMBB, Idx))
404 return VNI;
405
406 // Now for the fun part. We know that ParentVNI potentially has multiple defs,
407 // and we may need to create even more phi-defs to preserve VNInfo SSA form.
408 // Perform a depth-first search for predecessor blocks where we know the
409 // dominating VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
410
411 // Track MBBs where we have created or learned the dominating value.
412 // This may change during the DFS as we create new phi-defs.
413 typedef DenseMap<MachineBasicBlock*, VNInfo*> MBBValueMap;
414 MBBValueMap DomValue;
415
416 for (idf_iterator<MachineBasicBlock*>
417 IDFI = idf_begin(IdxMBB),
418 IDFE = idf_end(IdxMBB); IDFI != IDFE;) {
419 MachineBasicBlock *MBB = *IDFI;
420 SlotIndex End = lis_.getMBBEndIdx(MBB);
421
422 // We are operating on the restricted CFG where ParentVNI is live.
423 if (parentli_.getVNInfoAt(End.getPrevSlot()) != ParentVNI) {
424 IDFI.skipChildren();
425 continue;
426 }
427
428 // Do we have a dominating value in this block?
429 VNInfo *VNI = extendTo(MBB, End);
430 if (!VNI) {
431 ++IDFI;
432 continue;
433 }
434
435 // Yes, VNI dominates MBB. Track the path back to IdxMBB, creating phi-defs
436 // as needed along the way.
437 for (unsigned PI = IDFI.getPathLength()-1; PI != 0; --PI) {
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000438 // Start from MBB's immediate successor. End at IdxMBB.
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000439 MachineBasicBlock *Succ = IDFI.getPath(PI-1);
440 std::pair<MBBValueMap::iterator, bool> InsP =
441 DomValue.insert(MBBValueMap::value_type(Succ, VNI));
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000442
443 // This is the first time we backtrack to Succ.
444 if (InsP.second)
445 continue;
446
447 // We reached Succ again with the same VNI. Nothing is going to change.
448 VNInfo *OVNI = InsP.first->second;
449 if (OVNI == VNI)
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000450 break;
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000451
452 // Succ already has a phi-def. No need to continue.
453 SlotIndex Start = lis_.getMBBStartIdx(Succ);
454 if (OVNI->def == Start)
455 break;
456
457 // We have a collision between the old and new VNI at Succ. That means
458 // neither dominates and we need a new phi-def.
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000459 VNI = li_->getNextValue(Start, 0, true, lis_.getVNInfoAllocator());
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000460 VNI->setIsPHIDef(true);
461 InsP.first->second = VNI;
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000462
463 // Replace OVNI with VNI in the remaining path.
464 for (; PI > 1 ; --PI) {
465 MBBValueMap::iterator I = DomValue.find(IDFI.getPath(PI-2));
466 if (I == DomValue.end() || I->second != OVNI)
467 break;
468 I->second = VNI;
469 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000470 }
471
472 // No need to search the children, we found a dominating value.
Jakob Stoklund Olesencf16bea2010-08-18 20:06:05 +0000473 IDFI.skipChildren();
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000474 }
475
476 // The search should at least find a dominating value for IdxMBB.
477 assert(!DomValue.empty() && "Couldn't find a reaching definition");
478
479 // Since we went through the trouble of a full DFS visiting all reaching defs,
480 // the values in DomValue are now accurate. No more phi-defs are needed for
481 // these blocks, so we can color the live ranges.
482 // This makes the next mapValue call much faster.
483 VNInfo *IdxVNI = 0;
484 for (MBBValueMap::iterator I = DomValue.begin(), E = DomValue.end(); I != E;
485 ++I) {
486 MachineBasicBlock *MBB = I->first;
487 VNInfo *VNI = I->second;
488 SlotIndex Start = lis_.getMBBStartIdx(MBB);
489 if (MBB == IdxMBB) {
490 // Don't add full liveness to IdxMBB, stop at Idx.
491 if (Start != Idx)
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000492 li_->addRange(LiveRange(Start, Idx, VNI));
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000493 // The caller had better add some liveness to IdxVNI, or it leaks.
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000494 IdxVNI = VNI;
495 } else
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000496 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000497 }
498
499 assert(IdxVNI && "Didn't find value for Idx");
500 return IdxVNI;
501}
502
503// extendTo - Find the last li_ value defined in MBB at or before Idx. The
504// parentli_ is assumed to be live at Idx. Extend the live range to Idx.
505// Return the found VNInfo, or NULL.
506VNInfo *LiveIntervalMap::extendTo(MachineBasicBlock *MBB, SlotIndex Idx) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000507 assert(li_ && "call reset first");
508 LiveInterval::iterator I = std::upper_bound(li_->begin(), li_->end(), Idx);
509 if (I == li_->begin())
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000510 return 0;
511 --I;
512 if (I->start < lis_.getMBBStartIdx(MBB))
513 return 0;
514 if (I->end < Idx)
515 I->end = Idx;
516 return I->valno;
517}
518
519// addSimpleRange - Add a simple range from parentli_ to li_.
520// ParentVNI must be live in the [Start;End) interval.
521void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End,
522 const VNInfo *ParentVNI) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000523 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000524 VNInfo *VNI = mapValue(ParentVNI, Start);
525 // A simple mappoing is easy.
526 if (VNI->def == ParentVNI->def) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000527 li_->addRange(LiveRange(Start, End, VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000528 return;
529 }
530
531 // ParentVNI is a complex value. We must map per MBB.
532 MachineFunction::iterator MBB = lis_.getMBBFromIndex(Start);
533 MachineFunction::iterator MBBE = lis_.getMBBFromIndex(End);
534
535 if (MBB == MBBE) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000536 li_->addRange(LiveRange(Start, End, VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000537 return;
538 }
539
540 // First block.
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000541 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000542
543 // Run sequence of full blocks.
544 for (++MBB; MBB != MBBE; ++MBB) {
545 Start = lis_.getMBBStartIdx(MBB);
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000546 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB),
547 mapValue(ParentVNI, Start)));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000548 }
549
550 // Final block.
551 Start = lis_.getMBBStartIdx(MBB);
552 if (Start != End)
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000553 li_->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start)));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000554}
555
556/// addRange - Add live ranges to li_ where [Start;End) intersects parentli_.
557/// All needed values whose def is not inside [Start;End) must be defined
558/// beforehand so mapValue will work.
559void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000560 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000561 LiveInterval::const_iterator B = parentli_.begin(), E = parentli_.end();
562 LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
563
564 // Check if --I begins before Start and overlaps.
565 if (I != B) {
566 --I;
567 if (I->end > Start)
568 addSimpleRange(Start, std::min(End, I->end), I->valno);
569 ++I;
570 }
571
572 // The remaining ranges begin after Start.
573 for (;I != E && I->start < End; ++I)
574 addSimpleRange(I->start, std::min(End, I->end), I->valno);
575}
576
577//===----------------------------------------------------------------------===//
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() {
603 unsigned curli = sa_.getCurLI()->reg;
604 unsigned Reg = mri_.createVirtualRegister(mri_.getRegClass(curli));
605 LiveInterval &Intv = lis_.getOrCreateInterval(Reg);
606 vrm_.grow();
607 vrm_.assignVirt2StackSlot(Reg, vrm_.getStackSlot(curli));
608 return &Intv;
609}
610
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000611LiveInterval *SplitEditor::getDupLI() {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000612 if (!dupli_.getLI()) {
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000613 // Create an interval for dupli that is a copy of curli.
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000614 dupli_.reset(createInterval());
615 dupli_.getLI()->Copy(*curli_, &mri_, lis_.getVNInfoAllocator());
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000616 }
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000617 return dupli_.getLI();
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000618}
619
620VNInfo *SplitEditor::mapValue(const VNInfo *curliVNI) {
621 VNInfo *&VNI = valueMap_[curliVNI];
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000622 if (!VNI)
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000623 VNI = openli_.getLI()->createValueCopy(curliVNI, lis_.getVNInfoAllocator());
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000624 return VNI;
625}
626
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000627/// Insert a COPY instruction curli -> li. Allocate a new value from li
628/// defined by the COPY. Note that rewrite() will deal with the curli
629/// register, so this function can be used to copy from any interval - openli,
630/// curli, or dupli.
631VNInfo *SplitEditor::insertCopy(LiveInterval &LI,
632 MachineBasicBlock &MBB,
633 MachineBasicBlock::iterator I) {
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000634 MachineInstr *MI = BuildMI(MBB, I, DebugLoc(), tii_.get(TargetOpcode::COPY),
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000635 LI.reg).addReg(curli_->reg);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000636 SlotIndex DefIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
637 return LI.getNextValue(DefIdx, MI, true, lis_.getVNInfoAllocator());
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000638}
639
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000640/// Create a new virtual register and live interval.
641void SplitEditor::openIntv() {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000642 assert(!openli_.getLI() && "Previous LI not closed before openIntv");
643 openli_.reset(createInterval());
644 intervals_.push_back(openli_.getLI());
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000645 liveThrough_ = false;
646}
647
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000648/// enterIntvBefore - Enter openli before the instruction at Idx. If curli is
649/// not live before Idx, a COPY is not inserted.
650void SplitEditor::enterIntvBefore(SlotIndex Idx) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000651 assert(openli_.getLI() && "openIntv not called before enterIntvBefore");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000652
653 // Copy from curli_ if it is live.
654 if (VNInfo *CurVNI = curli_->getVNInfoAt(Idx.getUseIndex())) {
655 MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
656 assert(MI && "enterIntvBefore called with invalid index");
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000657 VNInfo *VNI = insertCopy(*openli_.getLI(), *MI->getParent(), MI);
658 openli_.getLI()->addRange(LiveRange(VNI->def, Idx.getDefIndex(), VNI));
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000659
660 // Make sure CurVNI is properly mapped.
661 VNInfo *&mapVNI = valueMap_[CurVNI];
662 // We dont have SSA update yet, so only one entry per value is allowed.
663 assert(!mapVNI && "enterIntvBefore called more than once for the same value");
664 mapVNI = VNI;
665 }
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000666 DEBUG(dbgs() << " enterIntvBefore " << Idx << ": " << *openli_.getLI()
667 << '\n');
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000668}
669
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000670/// enterIntvAtEnd - Enter openli at the end of MBB.
671/// PhiMBB is a successor inside openli where a PHI value is created.
672/// Currently, all entries must share the same PhiMBB.
673void SplitEditor::enterIntvAtEnd(MachineBasicBlock &A, MachineBasicBlock &B) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000674 assert(openli_.getLI() && "openIntv not called before enterIntvAtEnd");
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000675
676 SlotIndex EndA = lis_.getMBBEndIdx(&A);
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000677 VNInfo *CurVNIA = curli_->getVNInfoAt(EndA.getPrevIndex());
678 if (!CurVNIA) {
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000679 DEBUG(dbgs() << " enterIntvAtEnd, curli not live out of BB#"
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000680 << A.getNumber() << ".\n");
681 return;
682 }
683
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000684 // Add a phi kill value and live range out of A.
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000685 VNInfo *VNIA = insertCopy(*openli_.getLI(), A, A.getFirstTerminator());
686 openli_.getLI()->addRange(LiveRange(VNIA->def, EndA, VNIA));
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000687
688 // FIXME: If this is the only entry edge, we don't need the extra PHI value.
689 // FIXME: If there are multiple entry blocks (so not a loop), we need proper
690 // SSA update.
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000691
692 // Now look at the start of B.
693 SlotIndex StartB = lis_.getMBBStartIdx(&B);
694 SlotIndex EndB = lis_.getMBBEndIdx(&B);
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000695 const LiveRange *CurB = curli_->getLiveRangeContaining(StartB);
696 if (!CurB) {
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000697 DEBUG(dbgs() << " enterIntvAtEnd: curli not live in to BB#"
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000698 << B.getNumber() << ".\n");
699 return;
700 }
701
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000702 VNInfo *VNIB = openli_.getLI()->getVNInfoAt(StartB);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000703 if (!VNIB) {
704 // Create a phi value.
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000705 VNIB = openli_.getLI()->getNextValue(SlotIndex(StartB, true), 0, false,
706 lis_.getVNInfoAllocator());
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000707 VNIB->setIsPHIDef(true);
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000708 VNInfo *&mapVNI = valueMap_[CurB->valno];
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000709 if (mapVNI) {
710 // Multiple copies - must create PHI value.
711 abort();
712 } else {
713 // This is the first copy of dupLR. Mark the mapping.
714 mapVNI = VNIB;
715 }
716
717 }
718
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000719 DEBUG(dbgs() << " enterIntvAtEnd: " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000720}
721
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000722/// useIntv - indicate that all instructions in MBB should use openli.
723void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
724 useIntv(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB));
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000725}
726
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000727void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000728 assert(openli_.getLI() && "openIntv not called before useIntv");
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000729
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000730 // Map the curli values from the interval into openli_
731 LiveInterval::const_iterator B = curli_->begin(), E = curli_->end();
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000732 LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
733
734 if (I != B) {
735 --I;
Jakob Stoklund Olesen2780d3c2010-08-13 01:05:26 +0000736 // I begins before Start, but overlaps.
737 if (I->end > Start)
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000738 openli_.getLI()->addRange(LiveRange(Start, std::min(End, I->end),
739 mapValue(I->valno)));
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000740 ++I;
741 }
742
743 // The remaining ranges begin after Start.
744 for (;I != E && I->start < End; ++I)
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000745 openli_.getLI()->addRange(LiveRange(I->start, std::min(End, I->end),
746 mapValue(I->valno)));
747 DEBUG(dbgs() << " use [" << Start << ';' << End << "): "
748 << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000749}
750
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000751/// leaveIntvAfter - Leave openli after the instruction at Idx.
752void SplitEditor::leaveIntvAfter(SlotIndex Idx) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000753 assert(openli_.getLI() && "openIntv not called before leaveIntvAfter");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000754
755 const LiveRange *CurLR = curli_->getLiveRangeContaining(Idx.getDefIndex());
756 if (!CurLR || CurLR->end <= Idx.getBoundaryIndex()) {
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000757 DEBUG(dbgs() << " leaveIntvAfter " << Idx << ": not live\n");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000758 return;
759 }
760
761 // Was this value of curli live through openli?
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000762 if (!openli_.getLI()->liveAt(CurLR->valno->def)) {
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000763 DEBUG(dbgs() << " leaveIntvAfter " << Idx << ": using external value\n");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000764 liveThrough_ = true;
765 return;
766 }
767
768 // We are going to insert a back copy, so we must have a dupli_.
769 LiveRange *DupLR = getDupLI()->getLiveRangeContaining(Idx.getDefIndex());
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000770 assert(DupLR && "dupli not live into block, but curli is?");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000771
772 // Insert the COPY instruction.
773 MachineBasicBlock::iterator I = lis_.getInstructionFromIndex(Idx);
774 MachineInstr *MI = BuildMI(*I->getParent(), llvm::next(I), I->getDebugLoc(),
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000775 tii_.get(TargetOpcode::COPY), dupli_.getLI()->reg)
776 .addReg(openli_.getLI()->reg);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000777 SlotIndex CopyIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000778 openli_.getLI()->addRange(LiveRange(Idx.getDefIndex(), CopyIdx,
779 mapValue(CurLR->valno)));
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000780 DupLR->valno->def = CopyIdx;
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000781 DEBUG(dbgs() << " leaveIntvAfter " << Idx << ": " << *openli_.getLI()
782 << '\n');
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000783}
784
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000785/// leaveIntvAtTop - Leave the interval at the top of MBB.
786/// Currently, only one value can leave the interval.
787void SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000788 assert(openli_.getLI() && "openIntv not called before leaveIntvAtTop");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000789
790 SlotIndex Start = lis_.getMBBStartIdx(&MBB);
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000791 const LiveRange *CurLR = curli_->getLiveRangeContaining(Start);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000792
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000793 // Is curli even live-in to MBB?
794 if (!CurLR) {
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000795 DEBUG(dbgs() << " leaveIntvAtTop at " << Start << ": not live\n");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000796 return;
797 }
798
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000799 // Is curli defined by PHI at the beginning of MBB?
800 bool isPHIDef = CurLR->valno->isPHIDef() &&
801 CurLR->valno->def.getBaseIndex() == Start;
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000802
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000803 // If MBB is using a value of curli that was defined outside the openli range,
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000804 // we don't want to copy it back here.
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000805 if (!isPHIDef && !openli_.getLI()->liveAt(CurLR->valno->def)) {
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000806 DEBUG(dbgs() << " leaveIntvAtTop at " << Start
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000807 << ": using external value\n");
808 liveThrough_ = true;
809 return;
810 }
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000811
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000812 // We are going to insert a back copy, so we must have a dupli_.
813 LiveRange *DupLR = getDupLI()->getLiveRangeContaining(Start);
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000814 assert(DupLR && "dupli not live into block, but curli is?");
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000815
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000816 // Insert the COPY instruction.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000817 MachineInstr *MI = BuildMI(MBB, MBB.begin(), DebugLoc(),
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000818 tii_.get(TargetOpcode::COPY), dupli_.getLI()->reg)
819 .addReg(openli_.getLI()->reg);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000820 SlotIndex Idx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000821
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000822 // Adjust dupli and openli values.
823 if (isPHIDef) {
824 // dupli was already a PHI on entry to MBB. Simply insert an openli PHI,
825 // and shift the dupli def down to the COPY.
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000826 VNInfo *VNI = openli_.getLI()->getNextValue(SlotIndex(Start,true), 0, false,
827 lis_.getVNInfoAllocator());
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000828 VNI->setIsPHIDef(true);
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000829 openli_.getLI()->addRange(LiveRange(VNI->def, Idx, VNI));
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000830
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000831 dupli_.getLI()->removeRange(Start, Idx);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000832 DupLR->valno->def = Idx;
833 DupLR->valno->setIsPHIDef(false);
834 } else {
835 // The dupli value was defined somewhere inside the openli range.
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000836 DEBUG(dbgs() << " leaveIntvAtTop source value defined at "
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000837 << DupLR->valno->def << "\n");
838 // FIXME: We may not need a PHI here if all predecessors have the same
839 // value.
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000840 VNInfo *VNI = openli_.getLI()->getNextValue(SlotIndex(Start,true), 0, false,
841 lis_.getVNInfoAllocator());
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000842 VNI->setIsPHIDef(true);
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000843 openli_.getLI()->addRange(LiveRange(VNI->def, Idx, VNI));
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000844
845 // FIXME: What if DupLR->valno is used by multiple exits? SSA Update.
846
847 // closeIntv is going to remove the superfluous live ranges.
848 DupLR->valno->def = Idx;
849 DupLR->valno->setIsPHIDef(false);
850 }
851
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000852 DEBUG(dbgs() << " leaveIntvAtTop at " << Idx << ": " << *openli_.getLI()
853 << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000854}
855
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000856/// closeIntv - Indicate that we are done editing the currently open
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000857/// LiveInterval, and ranges can be trimmed.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000858void SplitEditor::closeIntv() {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000859 assert(openli_.getLI() && "openIntv not called before closeIntv");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000860
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000861 DEBUG(dbgs() << " closeIntv cleaning up\n");
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000862 DEBUG(dbgs() << " open " << *openli_.getLI() << '\n');
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000863
864 if (liveThrough_) {
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000865 DEBUG(dbgs() << " value live through region, leaving dupli as is.\n");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000866 } else {
867 // live out with copies inserted, or killed by region. Either way we need to
868 // remove the overlapping region from dupli.
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000869 getDupLI();
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000870 for (LiveInterval::iterator I = openli_.getLI()->begin(),
871 E = openli_.getLI()->end(); I != E; ++I) {
872 dupli_.getLI()->removeRange(I->start, I->end);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000873 }
874 // FIXME: A block branching to the entry block may also branch elsewhere
875 // curli is live. We need both openli and curli to be live in that case.
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000876 DEBUG(dbgs() << " dup2 " << *dupli_.getLI() << '\n');
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000877 }
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000878 openli_.reset(0);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000879 valueMap_.clear();
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000880}
881
882/// rewrite - after all the new live ranges have been created, rewrite
883/// instructions using curli to use the new intervals.
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000884bool SplitEditor::rewrite() {
885 assert(!openli_.getLI() && "Previous LI not closed before rewrite");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000886 const LiveInterval *curli = sa_.getCurLI();
887 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(curli->reg),
888 RE = mri_.reg_end(); RI != RE;) {
889 MachineOperand &MO = RI.getOperand();
890 MachineInstr *MI = MO.getParent();
891 ++RI;
892 if (MI->isDebugValue()) {
893 DEBUG(dbgs() << "Zapping " << *MI);
894 // FIXME: We can do much better with debug values.
895 MO.setReg(0);
896 continue;
897 }
898 SlotIndex Idx = lis_.getInstructionIndex(MI);
899 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000900 LiveInterval *LI = dupli_.getLI();
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000901 for (unsigned i = firstInterval, e = intervals_.size(); i != e; ++i) {
902 LiveInterval *testli = intervals_[i];
903 if (testli->liveAt(Idx)) {
904 LI = testli;
905 break;
906 }
907 }
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000908 if (LI) {
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000909 MO.setReg(LI->reg);
Jakob Stoklund Olesen00667a52010-08-13 01:05:23 +0000910 sa_.removeUse(MI);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000911 DEBUG(dbgs() << " rewrite " << Idx << '\t' << *MI);
912 }
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000913 }
914
915 // dupli_ goes in last, after rewriting.
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000916 if (dupli_.getLI()) {
917 if (dupli_.getLI()->empty()) {
Jakob Stoklund Olesen09c45d22010-08-12 23:02:57 +0000918 DEBUG(dbgs() << " dupli became empty?\n");
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000919 lis_.removeInterval(dupli_.getLI()->reg);
920 dupli_.reset(0);
Jakob Stoklund Olesen09c45d22010-08-12 23:02:57 +0000921 } else {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000922 dupli_.getLI()->RenumberValues(lis_);
923 intervals_.push_back(dupli_.getLI());
Jakob Stoklund Olesen09c45d22010-08-12 23:02:57 +0000924 }
Jakob Stoklund Olesen23436592010-08-06 18:46:59 +0000925 }
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000926
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +0000927 // Calculate spill weight and allocation hints for new intervals.
928 VirtRegAuxInfo vrai(vrm_.getMachineFunction(), lis_, sa_.loops_);
929 for (unsigned i = firstInterval, e = intervals_.size(); i != e; ++i) {
930 LiveInterval &li = *intervals_[i];
Jakob Stoklund Olesen9db3ea42010-08-10 18:37:40 +0000931 vrai.CalculateRegClass(li.reg);
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +0000932 vrai.CalculateWeightAndHint(li);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000933 DEBUG(dbgs() << " new interval " << mri_.getRegClass(li.reg)->getName()
934 << ":" << li << '\n');
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +0000935 }
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000936 return dupli_.getLI();
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000937}
938
939
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000940//===----------------------------------------------------------------------===//
941// Loop Splitting
942//===----------------------------------------------------------------------===//
943
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000944bool SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000945 SplitAnalysis::LoopBlocks Blocks;
946 sa_.getLoopBlocks(Loop, Blocks);
947
948 // Break critical edges as needed.
949 SplitAnalysis::BlockPtrSet CriticalExits;
950 sa_.getCriticalExits(Blocks, CriticalExits);
951 assert(CriticalExits.empty() && "Cannot break critical exits yet");
952
953 // Create new live interval for the loop.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000954 openIntv();
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000955
956 // Insert copies in the predecessors.
957 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
958 E = Blocks.Preds.end(); I != E; ++I) {
959 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000960 enterIntvAtEnd(MBB, *Loop->getHeader());
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000961 }
962
963 // Switch all loop blocks.
964 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
965 E = Blocks.Loop.end(); I != E; ++I)
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000966 useIntv(**I);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000967
968 // Insert back copies in the exit blocks.
969 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
970 E = Blocks.Exits.end(); I != E; ++I) {
971 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000972 leaveIntvAtTop(MBB);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000973 }
974
975 // Done.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000976 closeIntv();
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000977 return rewrite();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000978}
979
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000980
981//===----------------------------------------------------------------------===//
982// Single Block Splitting
983//===----------------------------------------------------------------------===//
984
985/// splitSingleBlocks - Split curli into a separate live interval inside each
986/// basic block in Blocks. Return true if curli has been completely replaced,
987/// false if curli is still intact, and needs to be spilled or split further.
988bool SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000989 DEBUG(dbgs() << " splitSingleBlocks for " << Blocks.size() << " blocks.\n");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000990 // Determine the first and last instruction using curli in each block.
991 typedef std::pair<SlotIndex,SlotIndex> IndexPair;
992 typedef DenseMap<const MachineBasicBlock*,IndexPair> IndexPairMap;
993 IndexPairMap MBBRange;
994 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
995 E = sa_.usingInstrs_.end(); I != E; ++I) {
996 const MachineBasicBlock *MBB = (*I)->getParent();
997 if (!Blocks.count(MBB))
998 continue;
999 SlotIndex Idx = lis_.getInstructionIndex(*I);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +00001000 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '\t' << Idx << '\t' << **I);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001001 IndexPair &IP = MBBRange[MBB];
1002 if (!IP.first.isValid() || Idx < IP.first)
1003 IP.first = Idx;
1004 if (!IP.second.isValid() || Idx > IP.second)
1005 IP.second = Idx;
1006 }
1007
1008 // Create a new interval for each block.
1009 for (SplitAnalysis::BlockPtrSet::const_iterator I = Blocks.begin(),
1010 E = Blocks.end(); I != E; ++I) {
1011 IndexPair &IP = MBBRange[*I];
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +00001012 DEBUG(dbgs() << " splitting for BB#" << (*I)->getNumber() << ": ["
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001013 << IP.first << ';' << IP.second << ")\n");
1014 assert(IP.first.isValid() && IP.second.isValid());
1015
1016 openIntv();
1017 enterIntvBefore(IP.first);
1018 useIntv(IP.first.getBaseIndex(), IP.second.getBoundaryIndex());
1019 leaveIntvAfter(IP.second);
1020 closeIntv();
1021 }
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +00001022 return rewrite();
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001023}
1024
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001025
1026//===----------------------------------------------------------------------===//
1027// Sub Block Splitting
1028//===----------------------------------------------------------------------===//
1029
1030/// getBlockForInsideSplit - If curli is contained inside a single basic block,
1031/// and it wou pay to subdivide the interval inside that block, return it.
1032/// Otherwise return NULL. The returned block can be passed to
1033/// SplitEditor::splitInsideBlock.
1034const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
1035 // The interval must be exclusive to one block.
1036 if (usingBlocks_.size() != 1)
1037 return 0;
1038 // Don't to this for less than 4 instructions. We want to be sure that
1039 // splitting actually reduces the instruction count per interval.
1040 if (usingInstrs_.size() < 4)
1041 return 0;
1042 return usingBlocks_.begin()->first;
1043}
1044
1045/// splitInsideBlock - Split curli into multiple intervals inside MBB. Return
1046/// true if curli has been completely replaced, false if curli is still
1047/// intact, and needs to be spilled or split further.
1048bool SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
1049 SmallVector<SlotIndex, 32> Uses;
1050 Uses.reserve(sa_.usingInstrs_.size());
1051 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1052 E = sa_.usingInstrs_.end(); I != E; ++I)
1053 if ((*I)->getParent() == MBB)
1054 Uses.push_back(lis_.getInstructionIndex(*I));
1055 DEBUG(dbgs() << " splitInsideBlock BB#" << MBB->getNumber() << " for "
1056 << Uses.size() << " instructions.\n");
1057 assert(Uses.size() >= 3 && "Need at least 3 instructions");
1058 array_pod_sort(Uses.begin(), Uses.end());
1059
1060 // Simple algorithm: Find the largest gap between uses as determined by slot
1061 // indices. Create new intervals for instructions before the gap and after the
1062 // gap.
1063 unsigned bestPos = 0;
1064 int bestGap = 0;
1065 DEBUG(dbgs() << " dist (" << Uses[0]);
1066 for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
1067 int g = Uses[i-1].distance(Uses[i]);
1068 DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
1069 if (g > bestGap)
1070 bestPos = i, bestGap = g;
1071 }
1072 DEBUG(dbgs() << "), best: -" << bestGap << "-\n");
1073
1074 // bestPos points to the first use after the best gap.
1075 assert(bestPos > 0 && "Invalid gap");
1076
1077 // FIXME: Don't create intervals for low densities.
1078
1079 // First interval before the gap. Don't create single-instr intervals.
1080 if (bestPos > 1) {
1081 openIntv();
1082 enterIntvBefore(Uses.front());
1083 useIntv(Uses.front().getBaseIndex(), Uses[bestPos-1].getBoundaryIndex());
1084 leaveIntvAfter(Uses[bestPos-1]);
1085 closeIntv();
1086 }
1087
1088 // Second interval after the gap.
1089 if (bestPos < Uses.size()-1) {
1090 openIntv();
1091 enterIntvBefore(Uses[bestPos]);
1092 useIntv(Uses[bestPos].getBaseIndex(), Uses.back().getBoundaryIndex());
1093 leaveIntvAfter(Uses.back());
1094 closeIntv();
1095 }
1096
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +00001097 return rewrite();
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001098}