blob: 4bb13e44b80face1b2360d0378491dd6efaf8fdf [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
Jakob Stoklund Olesen376dcbd2010-11-03 20:39:23 +000015#define DEBUG_TYPE "regalloc"
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000016#include "SplitKit.h"
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +000017#include "LiveRangeEdit.h"
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +000018#include "VirtRegMap.h"
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +000019#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000020#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Jakob Stoklund Olesend68f4582010-10-28 20:34:50 +000021#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +000022#include "llvm/CodeGen/MachineInstrBuilder.h"
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000023#include "llvm/CodeGen/MachineLoopInfo.h"
24#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000025#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000026#include "llvm/Support/Debug.h"
27#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000028#include "llvm/Target/TargetInstrInfo.h"
29#include "llvm/Target/TargetMachine.h"
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000030
31using namespace llvm;
32
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000033static cl::opt<bool>
34AllowSplit("spiller-splits-edges",
35 cl::desc("Allow critical edge splitting during spilling"));
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000036
37//===----------------------------------------------------------------------===//
38// Split Analysis
39//===----------------------------------------------------------------------===//
40
Jakob Stoklund Olesenf2c6e362010-07-20 23:50:15 +000041SplitAnalysis::SplitAnalysis(const MachineFunction &mf,
42 const LiveIntervals &lis,
43 const MachineLoopInfo &mli)
44 : mf_(mf),
45 lis_(lis),
46 loops_(mli),
47 tii_(*mf.getTarget().getInstrInfo()),
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000048 curli_(0) {}
49
50void SplitAnalysis::clear() {
51 usingInstrs_.clear();
52 usingBlocks_.clear();
53 usingLoops_.clear();
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +000054 curli_ = 0;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000055}
56
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000057bool SplitAnalysis::canAnalyzeBranch(const MachineBasicBlock *MBB) {
58 MachineBasicBlock *T, *F;
59 SmallVector<MachineOperand, 4> Cond;
60 return !tii_.AnalyzeBranch(const_cast<MachineBasicBlock&>(*MBB), T, F, Cond);
61}
62
Jakob Stoklund Olesenabff2802010-07-20 16:12:37 +000063/// analyzeUses - Count instructions, basic blocks, and loops using curli.
64void SplitAnalysis::analyzeUses() {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000065 const MachineRegisterInfo &MRI = mf_.getRegInfo();
66 for (MachineRegisterInfo::reg_iterator I = MRI.reg_begin(curli_->reg);
67 MachineInstr *MI = I.skipInstruction();) {
68 if (MI->isDebugValue() || !usingInstrs_.insert(MI))
69 continue;
70 MachineBasicBlock *MBB = MI->getParent();
71 if (usingBlocks_[MBB]++)
72 continue;
Jakob Stoklund Olesen9b90d7e2010-10-05 23:10:12 +000073 for (MachineLoop *Loop = loops_.getLoopFor(MBB); Loop;
74 Loop = Loop->getParentLoop())
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +000075 usingLoops_[Loop]++;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000076 }
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +000077 DEBUG(dbgs() << " counted "
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000078 << usingInstrs_.size() << " instrs, "
79 << usingBlocks_.size() << " blocks, "
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +000080 << usingLoops_.size() << " loops.\n");
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000081}
82
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +000083void SplitAnalysis::print(const BlockPtrSet &B, raw_ostream &OS) const {
84 for (BlockPtrSet::const_iterator I = B.begin(), E = B.end(); I != E; ++I) {
85 unsigned count = usingBlocks_.lookup(*I);
86 OS << " BB#" << (*I)->getNumber();
87 if (count)
88 OS << '(' << count << ')';
89 }
90}
91
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000092// Get three sets of basic blocks surrounding a loop: Blocks inside the loop,
93// predecessor blocks, and exit blocks.
94void SplitAnalysis::getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks) {
95 Blocks.clear();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000096
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000097 // Blocks in the loop.
98 Blocks.Loop.insert(Loop->block_begin(), Loop->block_end());
99
100 // Predecessor blocks.
101 const MachineBasicBlock *Header = Loop->getHeader();
102 for (MachineBasicBlock::const_pred_iterator I = Header->pred_begin(),
103 E = Header->pred_end(); I != E; ++I)
104 if (!Blocks.Loop.count(*I))
105 Blocks.Preds.insert(*I);
106
107 // Exit blocks.
108 for (MachineLoop::block_iterator I = Loop->block_begin(),
109 E = Loop->block_end(); I != E; ++I) {
110 const MachineBasicBlock *MBB = *I;
111 for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
112 SE = MBB->succ_end(); SI != SE; ++SI)
113 if (!Blocks.Loop.count(*SI))
114 Blocks.Exits.insert(*SI);
115 }
116}
117
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000118void SplitAnalysis::print(const LoopBlocks &B, raw_ostream &OS) const {
119 OS << "Loop:";
120 print(B.Loop, OS);
121 OS << ", preds:";
122 print(B.Preds, OS);
123 OS << ", exits:";
124 print(B.Exits, OS);
125}
126
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000127/// analyzeLoopPeripheralUse - Return an enum describing how curli_ is used in
128/// and around the Loop.
129SplitAnalysis::LoopPeripheralUse SplitAnalysis::
130analyzeLoopPeripheralUse(const SplitAnalysis::LoopBlocks &Blocks) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000131 LoopPeripheralUse use = ContainedInLoop;
132 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
133 I != E; ++I) {
134 const MachineBasicBlock *MBB = I->first;
135 // Is this a peripheral block?
136 if (use < MultiPeripheral &&
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000137 (Blocks.Preds.count(MBB) || Blocks.Exits.count(MBB))) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000138 if (I->second > 1) use = MultiPeripheral;
139 else use = SinglePeripheral;
140 continue;
141 }
142 // Is it a loop block?
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000143 if (Blocks.Loop.count(MBB))
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000144 continue;
145 // It must be an unrelated block.
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000146 DEBUG(dbgs() << ", outside: BB#" << MBB->getNumber());
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000147 return OutsideLoop;
148 }
149 return use;
150}
151
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000152/// getCriticalExits - It may be necessary to partially break critical edges
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000153/// leaving the loop if an exit block has predecessors from outside the loop
154/// periphery.
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000155void SplitAnalysis::getCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
156 BlockPtrSet &CriticalExits) {
157 CriticalExits.clear();
158
Jakob Stoklund Olesen0960a652010-10-27 00:39:05 +0000159 // A critical exit block has curli live-in, and has a predecessor that is not
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000160 // in the loop nor a loop predecessor. For such an exit block, the edges
161 // carrying the new variable must be moved to a new pre-exit block.
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000162 for (BlockPtrSet::iterator I = Blocks.Exits.begin(), E = Blocks.Exits.end();
163 I != E; ++I) {
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000164 const MachineBasicBlock *Exit = *I;
165 // A single-predecessor exit block is definitely not a critical edge.
166 if (Exit->pred_size() == 1)
167 continue;
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000168 // This exit may not have curli live in at all. No need to split.
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000169 if (!lis_.isLiveInToMBB(*curli_, Exit))
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000170 continue;
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000171 // Does this exit block have a predecessor that is not a loop block or loop
172 // predecessor?
173 for (MachineBasicBlock::const_pred_iterator PI = Exit->pred_begin(),
174 PE = Exit->pred_end(); PI != PE; ++PI) {
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000175 const MachineBasicBlock *Pred = *PI;
176 if (Blocks.Loop.count(Pred) || Blocks.Preds.count(Pred))
177 continue;
178 // This is a critical exit block, and we need to split the exit edge.
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000179 CriticalExits.insert(Exit);
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000180 break;
181 }
182 }
183}
184
Jakob Stoklund Olesen0960a652010-10-27 00:39:05 +0000185void SplitAnalysis::getCriticalPreds(const SplitAnalysis::LoopBlocks &Blocks,
186 BlockPtrSet &CriticalPreds) {
187 CriticalPreds.clear();
188
189 // A critical predecessor block has curli live-out, and has a successor that
190 // has curli live-in and is not in the loop nor a loop exit block. For such a
191 // predecessor block, we must carry the value in both the 'inside' and
192 // 'outside' registers.
193 for (BlockPtrSet::iterator I = Blocks.Preds.begin(), E = Blocks.Preds.end();
194 I != E; ++I) {
195 const MachineBasicBlock *Pred = *I;
196 // Definitely not a critical edge.
197 if (Pred->succ_size() == 1)
198 continue;
199 // This block may not have curli live out at all if there is a PHI.
200 if (!lis_.isLiveOutOfMBB(*curli_, Pred))
201 continue;
202 // Does this block have a successor outside the loop?
203 for (MachineBasicBlock::const_pred_iterator SI = Pred->succ_begin(),
204 SE = Pred->succ_end(); SI != SE; ++SI) {
205 const MachineBasicBlock *Succ = *SI;
206 if (Blocks.Loop.count(Succ) || Blocks.Exits.count(Succ))
207 continue;
208 if (!lis_.isLiveInToMBB(*curli_, Succ))
209 continue;
210 // This is a critical predecessor block.
211 CriticalPreds.insert(Pred);
212 break;
213 }
214 }
215}
216
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000217/// canSplitCriticalExits - Return true if it is possible to insert new exit
218/// blocks before the blocks in CriticalExits.
219bool
220SplitAnalysis::canSplitCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
221 BlockPtrSet &CriticalExits) {
222 // If we don't allow critical edge splitting, require no critical exits.
223 if (!AllowSplit)
224 return CriticalExits.empty();
225
226 for (BlockPtrSet::iterator I = CriticalExits.begin(), E = CriticalExits.end();
227 I != E; ++I) {
228 const MachineBasicBlock *Succ = *I;
229 // We want to insert a new pre-exit MBB before Succ, and change all the
230 // in-loop blocks to branch to the pre-exit instead of Succ.
231 // Check that all the in-loop predecessors can be changed.
232 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
233 PE = Succ->pred_end(); PI != PE; ++PI) {
234 const MachineBasicBlock *Pred = *PI;
235 // The external predecessors won't be altered.
236 if (!Blocks.Loop.count(Pred) && !Blocks.Preds.count(Pred))
237 continue;
238 if (!canAnalyzeBranch(Pred))
239 return false;
240 }
241
242 // If Succ's layout predecessor falls through, that too must be analyzable.
243 // We need to insert the pre-exit block in the gap.
244 MachineFunction::const_iterator MFI = Succ;
245 if (MFI == mf_.begin())
246 continue;
247 if (!canAnalyzeBranch(--MFI))
248 return false;
249 }
250 // No problems found.
251 return true;
252}
253
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000254void SplitAnalysis::analyze(const LiveInterval *li) {
255 clear();
256 curli_ = li;
Jakob Stoklund Olesenabff2802010-07-20 16:12:37 +0000257 analyzeUses();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000258}
259
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000260void SplitAnalysis::getSplitLoops(LoopPtrSet &Loops) {
261 assert(curli_ && "Call analyze() before getSplitLoops");
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000262 if (usingLoops_.empty())
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000263 return;
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000264
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000265 LoopBlocks Blocks;
266 BlockPtrSet CriticalExits;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000267
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000268 // We split around loops where curli is used outside the periphery.
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000269 for (LoopCountMap::const_iterator I = usingLoops_.begin(),
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000270 E = usingLoops_.end(); I != E; ++I) {
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000271 const MachineLoop *Loop = I->first;
272 getLoopBlocks(Loop, Blocks);
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000273 DEBUG({ dbgs() << " "; print(Blocks, dbgs()); });
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000274
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000275 switch(analyzeLoopPeripheralUse(Blocks)) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000276 case OutsideLoop:
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000277 break;
278 case MultiPeripheral:
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000279 // FIXME: We could split a live range with multiple uses in a peripheral
280 // block and still make progress. However, it is possible that splitting
281 // another live range will insert copies into a peripheral block, and
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000282 // there is a small chance we can enter an infinite loop, inserting copies
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000283 // forever.
284 // For safety, stick to splitting live ranges with uses outside the
285 // periphery.
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000286 DEBUG(dbgs() << ": multiple peripheral uses");
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000287 break;
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000288 case ContainedInLoop:
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000289 DEBUG(dbgs() << ": fully contained\n");
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000290 continue;
291 case SinglePeripheral:
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000292 DEBUG(dbgs() << ": single peripheral use\n");
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000293 continue;
294 }
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000295 // Will it be possible to split around this loop?
296 getCriticalExits(Blocks, CriticalExits);
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000297 DEBUG(dbgs() << ": " << CriticalExits.size() << " critical exits\n");
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000298 if (!canSplitCriticalExits(Blocks, CriticalExits))
299 continue;
300 // This is a possible split.
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000301 Loops.insert(Loop);
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000302 }
303
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000304 DEBUG(dbgs() << " getSplitLoops found " << Loops.size()
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000305 << " candidate loops.\n");
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000306}
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000307
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000308const MachineLoop *SplitAnalysis::getBestSplitLoop() {
309 LoopPtrSet Loops;
310 getSplitLoops(Loops);
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000311 if (Loops.empty())
312 return 0;
313
314 // Pick the earliest loop.
315 // FIXME: Are there other heuristics to consider?
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000316 const MachineLoop *Best = 0;
317 SlotIndex BestIdx;
318 for (LoopPtrSet::const_iterator I = Loops.begin(), E = Loops.end(); I != E;
319 ++I) {
320 SlotIndex Idx = lis_.getMBBStartIdx((*I)->getHeader());
321 if (!Best || Idx < BestIdx)
322 Best = *I, BestIdx = Idx;
323 }
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000324 DEBUG(dbgs() << " getBestSplitLoop found " << *Best);
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000325 return Best;
326}
327
Jakob Stoklund Olesen697483a2010-12-15 17:49:52 +0000328/// isBypassLoop - Return true if curli is live through Loop and has no uses
329/// inside the loop. Bypass loops are candidates for splitting because it can
330/// prevent interference inside the loop.
331bool SplitAnalysis::isBypassLoop(const MachineLoop *Loop) {
332 // If curli is live into the loop header and there are no uses in the loop, it
333 // must be live in the entire loop and live on at least one exiting edge.
334 return !usingLoops_.count(Loop) &&
335 lis_.isLiveInToMBB(*curli_, Loop->getHeader());
336}
337
338/// getBypassLoops - Get all the maximal bypass loops. These are the bypass
339/// loops whose parent is not a bypass loop.
340void SplitAnalysis::getBypassLoops(LoopPtrSet &BypassLoops) {
341 SmallVector<MachineLoop*, 8> Todo(loops_.begin(), loops_.end());
Jakob Stoklund Olesen62032952010-12-15 18:07:48 +0000342 while (!Todo.empty()) {
Jakob Stoklund Olesen697483a2010-12-15 17:49:52 +0000343 MachineLoop *Loop = Todo.pop_back_val();
344 if (!usingLoops_.count(Loop)) {
345 // This is either a bypass loop or completely irrelevant.
346 if (lis_.isLiveInToMBB(*curli_, Loop->getHeader()))
347 BypassLoops.insert(Loop);
348 // Either way, skip the child loops.
349 continue;
350 }
351
352 // The child loops may be bypass loops.
353 Todo.append(Loop->begin(), Loop->end());
354 }
355}
356
357
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000358//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000359// LiveIntervalMap
360//===----------------------------------------------------------------------===//
361
Jakob Stoklund Olesenb3e96812010-09-13 21:29:45 +0000362// Work around the fact that the std::pair constructors are broken for pointer
363// pairs in some implementations. makeVV(x, 0) works.
364static inline std::pair<const VNInfo*, VNInfo*>
365makeVV(const VNInfo *a, VNInfo *b) {
366 return std::make_pair(a, b);
367}
368
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000369void LiveIntervalMap::reset(LiveInterval *li) {
370 li_ = li;
371 valueMap_.clear();
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000372 liveOutCache_.clear();
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000373}
374
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000375bool LiveIntervalMap::isComplexMapped(const VNInfo *ParentVNI) const {
376 ValueMap::const_iterator i = valueMap_.find(ParentVNI);
377 return i != valueMap_.end() && i->second == 0;
378}
379
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000380// defValue - Introduce a li_ def for ParentVNI that could be later than
381// ParentVNI->def.
382VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000383 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000384 assert(ParentVNI && "Mapping NULL value");
385 assert(Idx.isValid() && "Invalid SlotIndex");
386 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
387
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000388 // Create a new value.
Lang Hames6e2968c2010-09-25 12:04:16 +0000389 VNInfo *VNI = li_->getNextValue(Idx, 0, lis_.getVNInfoAllocator());
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000390
Jakob Stoklund Olesen79c02622010-10-26 22:36:02 +0000391 // Preserve the PHIDef bit.
392 if (ParentVNI->isPHIDef() && Idx == ParentVNI->def)
393 VNI->setIsPHIDef(true);
394
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000395 // Use insert for lookup, so we can add missing values with a second lookup.
396 std::pair<ValueMap::iterator,bool> InsP =
397 valueMap_.insert(makeVV(ParentVNI, Idx == ParentVNI->def ? VNI : 0));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000398
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000399 // This is now a complex def. Mark with a NULL in valueMap.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000400 if (!InsP.second)
401 InsP.first->second = 0;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000402
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000403 return VNI;
404}
405
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000406
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000407// mapValue - Find the mapped value for ParentVNI at Idx.
408// Potentially create phi-def values.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000409VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx,
410 bool *simple) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000411 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000412 assert(ParentVNI && "Mapping NULL value");
413 assert(Idx.isValid() && "Invalid SlotIndex");
414 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
415
416 // Use insert for lookup, so we can add missing values with a second lookup.
417 std::pair<ValueMap::iterator,bool> InsP =
Jakob Stoklund Olesenb3e96812010-09-13 21:29:45 +0000418 valueMap_.insert(makeVV(ParentVNI, 0));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000419
420 // This was an unknown value. Create a simple mapping.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000421 if (InsP.second) {
422 if (simple) *simple = true;
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000423 return InsP.first->second = li_->createValueCopy(ParentVNI,
424 lis_.getVNInfoAllocator());
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000425 }
426
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000427 // This was a simple mapped value.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000428 if (InsP.first->second) {
429 if (simple) *simple = true;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000430 return InsP.first->second;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000431 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000432
433 // This is a complex mapped value. There may be multiple defs, and we may need
434 // to create phi-defs.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000435 if (simple) *simple = false;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000436 MachineBasicBlock *IdxMBB = lis_.getMBBFromIndex(Idx);
437 assert(IdxMBB && "No MBB at Idx");
438
439 // Is there a def in the same MBB we can extend?
440 if (VNInfo *VNI = extendTo(IdxMBB, Idx))
441 return VNI;
442
443 // Now for the fun part. We know that ParentVNI potentially has multiple defs,
444 // and we may need to create even more phi-defs to preserve VNInfo SSA form.
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000445 // Perform a search for all predecessor blocks where we know the dominating
446 // VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
447 DEBUG(dbgs() << "\n Reaching defs for BB#" << IdxMBB->getNumber()
448 << " at " << Idx << " in " << *li_ << '\n');
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000449
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000450 // Blocks where li_ should be live-in.
451 SmallVector<MachineDomTreeNode*, 16> LiveIn;
452 LiveIn.push_back(mdt_[IdxMBB]);
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000453
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000454 // Using liveOutCache_ as a visited set, perform a BFS for all reaching defs.
455 for (unsigned i = 0; i != LiveIn.size(); ++i) {
456 MachineBasicBlock *MBB = LiveIn[i]->getBlock();
457 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
458 PE = MBB->pred_end(); PI != PE; ++PI) {
459 MachineBasicBlock *Pred = *PI;
460 // Is this a known live-out block?
461 std::pair<LiveOutMap::iterator,bool> LOIP =
462 liveOutCache_.insert(std::make_pair(Pred, LiveOutPair()));
463 // Yes, we have been here before.
464 if (!LOIP.second) {
Benjamin Kramer8a8e26f2010-10-29 17:40:05 +0000465 DEBUG(if (VNInfo *VNI = LOIP.first->second.first)
466 dbgs() << " known valno #" << VNI->id
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000467 << " at BB#" << Pred->getNumber() << '\n');
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000468 continue;
469 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000470
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000471 // Does Pred provide a live-out value?
472 SlotIndex Last = lis_.getMBBEndIdx(Pred).getPrevSlot();
473 if (VNInfo *VNI = extendTo(Pred, Last)) {
474 MachineBasicBlock *DefMBB = lis_.getMBBFromIndex(VNI->def);
475 DEBUG(dbgs() << " found valno #" << VNI->id
Jakob Stoklund Olesenc94fcb12010-10-29 17:37:25 +0000476 << " from BB#" << DefMBB->getNumber()
477 << " at BB#" << Pred->getNumber() << '\n');
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000478 LiveOutPair &LOP = LOIP.first->second;
479 LOP.first = VNI;
Benjamin Kramer8a8e26f2010-10-29 17:40:05 +0000480 LOP.second = mdt_[DefMBB];
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000481 continue;
482 }
483 // No, we need a live-in value for Pred as well
484 if (Pred != IdxMBB)
485 LiveIn.push_back(mdt_[Pred]);
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000486 }
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000487 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000488
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000489 // We may need to add phi-def values to preserve the SSA form.
490 // This is essentially the same iterative algorithm that SSAUpdater uses,
491 // except we already have a dominator tree, so we don't have to recompute it.
492 VNInfo *IdxVNI = 0;
493 unsigned Changes;
494 do {
495 Changes = 0;
496 DEBUG(dbgs() << " Iterating over " << LiveIn.size() << " blocks.\n");
497 // Propagate live-out values down the dominator tree, inserting phi-defs when
498 // necessary. Since LiveIn was created by a BFS, going backwards makes it more
499 // likely for us to visit immediate dominators before their children.
500 for (unsigned i = LiveIn.size(); i; --i) {
501 MachineDomTreeNode *Node = LiveIn[i-1];
502 MachineBasicBlock *MBB = Node->getBlock();
503 MachineDomTreeNode *IDom = Node->getIDom();
504 LiveOutPair IDomValue;
505 // We need a live-in value to a block with no immediate dominator?
506 // This is probably an unreachable block that has survived somehow.
507 bool needPHI = !IDom;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000508
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000509 // Get the IDom live-out value.
510 if (!needPHI) {
511 LiveOutMap::iterator I = liveOutCache_.find(IDom->getBlock());
512 if (I != liveOutCache_.end())
513 IDomValue = I->second;
514 else
515 // If IDom is outside our set of live-out blocks, there must be new
516 // defs, and we need a phi-def here.
517 needPHI = true;
518 }
Jakob Stoklund Olesen984a7fc2010-10-05 20:36:28 +0000519
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000520 // IDom dominates all of our predecessors, but it may not be the immediate
521 // dominator. Check if any of them have live-out values that are properly
522 // dominated by IDom. If so, we need a phi-def here.
523 if (!needPHI) {
524 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
525 PE = MBB->pred_end(); PI != PE; ++PI) {
526 LiveOutPair Value = liveOutCache_[*PI];
527 if (!Value.first || Value.first == IDomValue.first)
528 continue;
529 // This predecessor is carrying something other than IDomValue.
530 // It could be because IDomValue hasn't propagated yet, or it could be
531 // because MBB is in the dominance frontier of that value.
532 if (mdt_.dominates(IDom, Value.second)) {
533 needPHI = true;
534 break;
535 }
536 }
537 }
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000538
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000539 // Create a phi-def if required.
540 if (needPHI) {
541 ++Changes;
542 SlotIndex Start = lis_.getMBBStartIdx(MBB);
543 VNInfo *VNI = li_->getNextValue(Start, 0, lis_.getVNInfoAllocator());
544 VNI->setIsPHIDef(true);
545 DEBUG(dbgs() << " - BB#" << MBB->getNumber()
546 << " phi-def #" << VNI->id << " at " << Start << '\n');
547 // We no longer need li_ to be live-in.
548 LiveIn.erase(LiveIn.begin()+(i-1));
549 // Blocks in LiveIn are either IdxMBB, or have a value live-through.
550 if (MBB == IdxMBB)
551 IdxVNI = VNI;
552 // Check if we need to update live-out info.
553 LiveOutMap::iterator I = liveOutCache_.find(MBB);
554 if (I == liveOutCache_.end() || I->second.second == Node) {
555 // We already have a live-out defined in MBB, so this must be IdxMBB.
556 assert(MBB == IdxMBB && "Adding phi-def to known live-out");
557 li_->addRange(LiveRange(Start, Idx.getNextSlot(), VNI));
558 } else {
559 // This phi-def is also live-out, so color the whole block.
560 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
561 I->second = LiveOutPair(VNI, Node);
562 }
563 } else if (IDomValue.first) {
Jakob Stoklund Olesenc94fcb12010-10-29 17:37:25 +0000564 // No phi-def here. Remember incoming value for IdxMBB.
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000565 if (MBB == IdxMBB)
566 IdxVNI = IDomValue.first;
Jakob Stoklund Olesenc94fcb12010-10-29 17:37:25 +0000567 // Propagate IDomValue if needed:
568 // MBB is live-out and doesn't define its own value.
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000569 LiveOutMap::iterator I = liveOutCache_.find(MBB);
Jakob Stoklund Olesenc94fcb12010-10-29 17:37:25 +0000570 if (I != liveOutCache_.end() && I->second.second != Node &&
571 I->second.first != IDomValue.first) {
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000572 ++Changes;
573 I->second = IDomValue;
574 DEBUG(dbgs() << " - BB#" << MBB->getNumber()
575 << " idom valno #" << IDomValue.first->id
576 << " from BB#" << IDom->getBlock()->getNumber() << '\n');
577 }
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000578 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000579 }
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000580 DEBUG(dbgs() << " - made " << Changes << " changes.\n");
581 } while (Changes);
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000582
583 assert(IdxVNI && "Didn't find value for Idx");
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000584
585#ifndef NDEBUG
586 // Check the liveOutCache_ invariants.
587 for (LiveOutMap::iterator I = liveOutCache_.begin(), E = liveOutCache_.end();
588 I != E; ++I) {
589 assert(I->first && "Null MBB entry in cache");
590 assert(I->second.first && "Null VNInfo in cache");
591 assert(I->second.second && "Null DomTreeNode in cache");
592 if (I->second.second->getBlock() == I->first)
593 continue;
594 for (MachineBasicBlock::pred_iterator PI = I->first->pred_begin(),
595 PE = I->first->pred_end(); PI != PE; ++PI)
596 assert(liveOutCache_.lookup(*PI) == I->second && "Bad invariant");
597 }
598#endif
599
600 // Since we went through the trouble of a full BFS visiting all reaching defs,
601 // the values in LiveIn are now accurate. No more phi-defs are needed
602 // for these blocks, so we can color the live ranges.
603 // This makes the next mapValue call much faster.
604 for (unsigned i = 0, e = LiveIn.size(); i != e; ++i) {
605 MachineBasicBlock *MBB = LiveIn[i]->getBlock();
606 SlotIndex Start = lis_.getMBBStartIdx(MBB);
607 if (MBB == IdxMBB) {
608 li_->addRange(LiveRange(Start, Idx.getNextSlot(), IdxVNI));
609 continue;
610 }
611 // Anything in LiveIn other than IdxMBB is live-through.
612 VNInfo *VNI = liveOutCache_.lookup(MBB).first;
613 assert(VNI && "Missing block value");
614 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
615 }
616
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000617 return IdxVNI;
618}
619
620// extendTo - Find the last li_ value defined in MBB at or before Idx. The
621// parentli_ is assumed to be live at Idx. Extend the live range to Idx.
622// Return the found VNInfo, or NULL.
Jakob Stoklund Olesenc95c1462010-10-27 00:39:07 +0000623VNInfo *LiveIntervalMap::extendTo(const MachineBasicBlock *MBB, SlotIndex Idx) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000624 assert(li_ && "call reset first");
625 LiveInterval::iterator I = std::upper_bound(li_->begin(), li_->end(), Idx);
626 if (I == li_->begin())
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000627 return 0;
628 --I;
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000629 if (I->end <= lis_.getMBBStartIdx(MBB))
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000630 return 0;
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000631 if (I->end <= Idx)
632 I->end = Idx.getNextSlot();
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000633 return I->valno;
634}
635
636// addSimpleRange - Add a simple range from parentli_ to li_.
637// ParentVNI must be live in the [Start;End) interval.
638void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End,
639 const VNInfo *ParentVNI) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000640 assert(li_ && "call reset first");
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000641 bool simple;
642 VNInfo *VNI = mapValue(ParentVNI, Start, &simple);
643 // A simple mapping is easy.
644 if (simple) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000645 li_->addRange(LiveRange(Start, End, VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000646 return;
647 }
648
649 // ParentVNI is a complex value. We must map per MBB.
650 MachineFunction::iterator MBB = lis_.getMBBFromIndex(Start);
Jakob Stoklund Olesendbc36092010-10-05 22:19:29 +0000651 MachineFunction::iterator MBBE = lis_.getMBBFromIndex(End.getPrevSlot());
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000652
653 if (MBB == MBBE) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000654 li_->addRange(LiveRange(Start, End, VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000655 return;
656 }
657
658 // First block.
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000659 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000660
661 // Run sequence of full blocks.
662 for (++MBB; MBB != MBBE; ++MBB) {
663 Start = lis_.getMBBStartIdx(MBB);
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000664 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB),
665 mapValue(ParentVNI, Start)));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000666 }
667
668 // Final block.
669 Start = lis_.getMBBStartIdx(MBB);
670 if (Start != End)
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000671 li_->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start)));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000672}
673
674/// addRange - Add live ranges to li_ where [Start;End) intersects parentli_.
675/// All needed values whose def is not inside [Start;End) must be defined
676/// beforehand so mapValue will work.
677void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000678 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000679 LiveInterval::const_iterator B = parentli_.begin(), E = parentli_.end();
680 LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
681
682 // Check if --I begins before Start and overlaps.
683 if (I != B) {
684 --I;
685 if (I->end > Start)
686 addSimpleRange(Start, std::min(End, I->end), I->valno);
687 ++I;
688 }
689
690 // The remaining ranges begin after Start.
691 for (;I != E && I->start < End; ++I)
692 addSimpleRange(I->start, std::min(End, I->end), I->valno);
693}
694
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000695
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000696//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000697// Split Editor
698//===----------------------------------------------------------------------===//
699
700/// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
Jakob Stoklund Olesend68f4582010-10-28 20:34:50 +0000701SplitEditor::SplitEditor(SplitAnalysis &sa,
702 LiveIntervals &lis,
703 VirtRegMap &vrm,
704 MachineDominatorTree &mdt,
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000705 LiveRangeEdit &edit)
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000706 : sa_(sa), lis_(lis), vrm_(vrm),
707 mri_(vrm.getMachineFunction().getRegInfo()),
708 tii_(*vrm.getMachineFunction().getTarget().getInstrInfo()),
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000709 tri_(*vrm.getMachineFunction().getTarget().getRegisterInfo()),
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000710 edit_(edit),
Jakob Stoklund Olesend68f4582010-10-28 20:34:50 +0000711 dupli_(lis_, mdt, edit.getParent()),
712 openli_(lis_, mdt, edit.getParent())
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000713{
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000714 // We don't need an AliasAnalysis since we will only be performing
715 // cheap-as-a-copy remats anyway.
716 edit_.anyRematerializable(lis_, tii_, 0);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000717}
718
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000719bool SplitEditor::intervalsLiveAt(SlotIndex Idx) const {
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000720 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I)
721 if (*I != dupli_.getLI() && (*I)->liveAt(Idx))
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000722 return true;
723 return false;
724}
725
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000726VNInfo *SplitEditor::defFromParent(LiveIntervalMap &Reg,
727 VNInfo *ParentVNI,
728 SlotIndex UseIdx,
729 MachineBasicBlock &MBB,
730 MachineBasicBlock::iterator I) {
731 VNInfo *VNI = 0;
732 MachineInstr *CopyMI = 0;
733 SlotIndex Def;
734
735 // Attempt cheap-as-a-copy rematerialization.
736 LiveRangeEdit::Remat RM(ParentVNI);
737 if (edit_.canRematerializeAt(RM, UseIdx, true, lis_)) {
738 Def = edit_.rematerializeAt(MBB, I, Reg.getLI()->reg, RM,
739 lis_, tii_, tri_);
740 } else {
741 // Can't remat, just insert a copy from parent.
742 CopyMI = BuildMI(MBB, I, DebugLoc(), tii_.get(TargetOpcode::COPY),
743 Reg.getLI()->reg).addReg(edit_.getReg());
744 Def = lis_.InsertMachineInstrInMaps(CopyMI).getDefIndex();
745 }
746
747 // Define the value in Reg.
748 VNI = Reg.defValue(ParentVNI, Def);
749 VNI->setCopy(CopyMI);
750
751 // Add minimal liveness for the new value.
752 if (UseIdx < Def)
753 UseIdx = Def;
754 Reg.getLI()->addRange(LiveRange(Def, UseIdx.getNextSlot(), VNI));
755 return VNI;
756}
757
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000758/// Create a new virtual register and live interval.
759void SplitEditor::openIntv() {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000760 assert(!openli_.getLI() && "Previous LI not closed before openIntv");
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000761 if (!dupli_.getLI())
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000762 dupli_.reset(&edit_.create(mri_, lis_, vrm_));
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000763
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000764 openli_.reset(&edit_.create(mri_, lis_, vrm_));
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000765}
766
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000767/// enterIntvBefore - Enter openli before the instruction at Idx. If curli is
768/// not live before Idx, a COPY is not inserted.
769void SplitEditor::enterIntvBefore(SlotIndex Idx) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000770 assert(openli_.getLI() && "openIntv not called before enterIntvBefore");
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000771 Idx = Idx.getUseIndex();
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000772 DEBUG(dbgs() << " enterIntvBefore " << Idx);
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000773 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000774 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000775 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000776 return;
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000777 }
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000778 DEBUG(dbgs() << ": valno " << ParentVNI->id);
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000779 truncatedValues.insert(ParentVNI);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000780 MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
781 assert(MI && "enterIntvBefore called with invalid index");
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000782
783 defFromParent(openli_, ParentVNI, Idx, *MI->getParent(), MI);
784
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000785 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000786}
787
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000788/// enterIntvAtEnd - Enter openli at the end of MBB.
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000789void SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000790 assert(openli_.getLI() && "openIntv not called before enterIntvAtEnd");
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000791 SlotIndex End = lis_.getMBBEndIdx(&MBB).getPrevSlot();
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000792 DEBUG(dbgs() << " enterIntvAtEnd BB#" << MBB.getNumber() << ", " << End);
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000793 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(End);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000794 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000795 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000796 return;
797 }
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000798 DEBUG(dbgs() << ": valno " << ParentVNI->id);
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000799 truncatedValues.insert(ParentVNI);
Jakob Stoklund Olesenb5f327b2010-11-10 23:56:00 +0000800 defFromParent(openli_, ParentVNI, End, MBB, MBB.getFirstTerminator());
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000801 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000802}
803
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000804/// useIntv - indicate that all instructions in MBB should use openli.
805void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
806 useIntv(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB));
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000807}
808
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000809void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000810 assert(openli_.getLI() && "openIntv not called before useIntv");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000811 openli_.addRange(Start, End);
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000812 DEBUG(dbgs() << " use [" << Start << ';' << End << "): "
813 << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000814}
815
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000816/// leaveIntvAfter - Leave openli after the instruction at Idx.
817void SplitEditor::leaveIntvAfter(SlotIndex Idx) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000818 assert(openli_.getLI() && "openIntv not called before leaveIntvAfter");
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000819 DEBUG(dbgs() << " leaveIntvAfter " << Idx);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000820
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000821 // The interval must be live beyond the instruction at Idx.
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000822 Idx = Idx.getBoundaryIndex();
823 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000824 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000825 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000826 return;
827 }
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000828 DEBUG(dbgs() << ": valno " << ParentVNI->id);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000829
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000830 MachineBasicBlock::iterator MII = lis_.getInstructionFromIndex(Idx);
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000831 VNInfo *VNI = defFromParent(dupli_, ParentVNI, Idx,
832 *MII->getParent(), llvm::next(MII));
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000833
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000834 // Make sure that openli is properly extended from Idx to the new copy.
835 // FIXME: This shouldn't be necessary for remats.
836 openli_.addSimpleRange(Idx, VNI->def, ParentVNI);
837
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000838 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000839}
840
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000841/// leaveIntvAtTop - Leave the interval at the top of MBB.
842/// Currently, only one value can leave the interval.
843void SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000844 assert(openli_.getLI() && "openIntv not called before leaveIntvAtTop");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000845 SlotIndex Start = lis_.getMBBStartIdx(&MBB);
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000846 DEBUG(dbgs() << " leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000847
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000848 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Start);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000849 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000850 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000851 return;
852 }
853
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000854 VNInfo *VNI = defFromParent(dupli_, ParentVNI, Start, MBB,
855 MBB.SkipPHIsAndLabels(MBB.begin()));
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000856
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000857 // Finally we must make sure that openli is properly extended from Start to
858 // the new copy.
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000859 openli_.addSimpleRange(Start, VNI->def, ParentVNI);
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000860 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000861}
862
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000863/// closeIntv - Indicate that we are done editing the currently open
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000864/// LiveInterval, and ranges can be trimmed.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000865void SplitEditor::closeIntv() {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000866 assert(openli_.getLI() && "openIntv not called before closeIntv");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000867
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000868 DEBUG(dbgs() << " closeIntv cleaning up\n");
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000869 DEBUG(dbgs() << " open " << *openli_.getLI() << '\n');
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000870 openli_.reset(0);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000871}
872
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000873/// rewrite - Rewrite all uses of reg to use the new registers.
874void SplitEditor::rewrite(unsigned reg) {
875 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(reg),
876 RE = mri_.reg_end(); RI != RE;) {
877 MachineOperand &MO = RI.getOperand();
Jakob Stoklund Olesen79cb53c2010-11-01 21:51:29 +0000878 unsigned OpNum = RI.getOperandNo();
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000879 MachineInstr *MI = MO.getParent();
880 ++RI;
881 if (MI->isDebugValue()) {
882 DEBUG(dbgs() << "Zapping " << *MI);
883 // FIXME: We can do much better with debug values.
884 MO.setReg(0);
885 continue;
886 }
887 SlotIndex Idx = lis_.getInstructionIndex(MI);
888 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
889 LiveInterval *LI = 0;
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000890 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E;
891 ++I) {
892 LiveInterval *testli = *I;
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000893 if (testli->liveAt(Idx)) {
894 LI = testli;
895 break;
896 }
897 }
Jakob Stoklund Olesen9d999772010-10-21 18:47:08 +0000898 DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t'<< Idx);
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000899 assert(LI && "No register was live at use");
900 MO.setReg(LI->reg);
Jakob Stoklund Olesen79cb53c2010-11-01 21:51:29 +0000901 if (MO.isUse() && !MI->isRegTiedToDefOperand(OpNum))
902 MO.setIsKill(LI->killedAt(Idx.getDefIndex()));
Jakob Stoklund Olesen9d999772010-10-21 18:47:08 +0000903 DEBUG(dbgs() << '\t' << *MI);
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000904 }
905}
906
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000907void
908SplitEditor::addTruncSimpleRange(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000909 // Build vector of iterator pairs from the intervals.
910 typedef std::pair<LiveInterval::const_iterator,
911 LiveInterval::const_iterator> IIPair;
912 SmallVector<IIPair, 8> Iters;
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000913 for (LiveRangeEdit::iterator LI = edit_.begin(), LE = edit_.end(); LI != LE;
914 ++LI) {
Jakob Stoklund Olesen9d999772010-10-21 18:47:08 +0000915 if (*LI == dupli_.getLI())
916 continue;
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000917 LiveInterval::const_iterator I = (*LI)->find(Start);
918 LiveInterval::const_iterator E = (*LI)->end();
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000919 if (I != E)
920 Iters.push_back(std::make_pair(I, E));
921 }
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000922
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000923 SlotIndex sidx = Start;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000924 // Break [Start;End) into segments that don't overlap any intervals.
925 for (;;) {
926 SlotIndex next = sidx, eidx = End;
927 // Find overlapping intervals.
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000928 for (unsigned i = 0; i != Iters.size() && sidx < eidx; ++i) {
929 LiveInterval::const_iterator I = Iters[i].first;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000930 // Interval I is overlapping [sidx;eidx). Trim sidx.
931 if (I->start <= sidx) {
932 sidx = I->end;
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000933 // Move to the next run, remove iters when all are consumed.
934 I = ++Iters[i].first;
935 if (I == Iters[i].second) {
936 Iters.erase(Iters.begin() + i);
937 --i;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000938 continue;
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000939 }
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000940 }
941 // Trim eidx too if needed.
942 if (I->start >= eidx)
943 continue;
944 eidx = I->start;
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000945 next = I->end;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000946 }
947 // Now, [sidx;eidx) doesn't overlap anything in intervals_.
948 if (sidx < eidx)
949 dupli_.addSimpleRange(sidx, eidx, VNI);
950 // If the interval end was truncated, we can try again from next.
951 if (next <= sidx)
952 break;
953 sidx = next;
954 }
955}
956
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000957void SplitEditor::computeRemainder() {
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000958 // First we need to fill in the live ranges in dupli.
959 // If values were redefined, we need a full recoloring with SSA update.
960 // If values were truncated, we only need to truncate the ranges.
961 // If values were partially rematted, we should shrink to uses.
962 // If values were fully rematted, they should be omitted.
963 // FIXME: If a single value is redefined, just move the def and truncate.
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000964 LiveInterval &parent = edit_.getParent();
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000965
966 // Values that are fully contained in the split intervals.
967 SmallPtrSet<const VNInfo*, 8> deadValues;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000968 // Map all curli values that should have live defs in dupli.
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000969 for (LiveInterval::const_vni_iterator I = parent.vni_begin(),
970 E = parent.vni_end(); I != E; ++I) {
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000971 const VNInfo *VNI = *I;
Jakob Stoklund Olesen3ccfce02010-10-29 17:47:49 +0000972 // Don't transfer unused values to the new intervals.
973 if (VNI->isUnused())
974 continue;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000975 // Original def is contained in the split intervals.
976 if (intervalsLiveAt(VNI->def)) {
977 // Did this value escape?
978 if (dupli_.isMapped(VNI))
979 truncatedValues.insert(VNI);
980 else
981 deadValues.insert(VNI);
982 continue;
983 }
984 // Add minimal live range at the definition.
985 VNInfo *DVNI = dupli_.defValue(VNI, VNI->def);
986 dupli_.getLI()->addRange(LiveRange(VNI->def, VNI->def.getNextSlot(), DVNI));
987 }
988
989 // Add all ranges to dupli.
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000990 for (LiveInterval::const_iterator I = parent.begin(), E = parent.end();
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000991 I != E; ++I) {
992 const LiveRange &LR = *I;
993 if (truncatedValues.count(LR.valno)) {
994 // recolor after removing intervals_.
995 addTruncSimpleRange(LR.start, LR.end, LR.valno);
996 } else if (!deadValues.count(LR.valno)) {
997 // recolor without truncation.
998 dupli_.addSimpleRange(LR.start, LR.end, LR.valno);
999 }
1000 }
Jakob Stoklund Olesenc95c1462010-10-27 00:39:07 +00001001
1002 // Extend dupli_ to be live out of any critical loop predecessors.
1003 // This means we have multiple registers live out of those blocks.
1004 // The alternative would be to split the critical edges.
1005 if (criticalPreds_.empty())
1006 return;
1007 for (SplitAnalysis::BlockPtrSet::iterator I = criticalPreds_.begin(),
1008 E = criticalPreds_.end(); I != E; ++I)
1009 dupli_.extendTo(*I, lis_.getMBBEndIdx(*I).getPrevSlot());
1010 criticalPreds_.clear();
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +00001011}
1012
1013void SplitEditor::finish() {
1014 assert(!openli_.getLI() && "Previous LI not closed before rewrite");
1015 assert(dupli_.getLI() && "No dupli for rewrite. Noop spilt?");
1016
1017 // Complete dupli liveness.
1018 computeRemainder();
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +00001019
Jakob Stoklund Olesen0253df92010-10-07 23:34:34 +00001020 // Get rid of unused values and set phi-kill flags.
Jakob Stoklund Olesenf1354ae2010-10-26 22:36:05 +00001021 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I)
1022 (*I)->RenumberValues(lis_);
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +00001023
Jakob Stoklund Olesen0253df92010-10-07 23:34:34 +00001024 // Rewrite instructions.
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +00001025 rewrite(edit_.getReg());
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +00001026
Jakob Stoklund Olesen3a0e0712010-10-26 22:36:09 +00001027 // Now check if any registers were separated into multiple components.
1028 ConnectedVNInfoEqClasses ConEQ(lis_);
1029 for (unsigned i = 0, e = edit_.size(); i != e; ++i) {
1030 // Don't use iterators, they are invalidated by create() below.
1031 LiveInterval *li = edit_.get(i);
1032 unsigned NumComp = ConEQ.Classify(li);
1033 if (NumComp <= 1)
1034 continue;
1035 DEBUG(dbgs() << " " << NumComp << " components: " << *li << '\n');
1036 SmallVector<LiveInterval*, 8> dups;
1037 dups.push_back(li);
1038 for (unsigned i = 1; i != NumComp; ++i)
1039 dups.push_back(&edit_.create(mri_, lis_, vrm_));
1040 ConEQ.Distribute(&dups[0]);
1041 // Rewrite uses to the new regs.
1042 rewrite(li->reg);
1043 }
1044
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +00001045 // Calculate spill weight and allocation hints for new intervals.
1046 VirtRegAuxInfo vrai(vrm_.getMachineFunction(), lis_, sa_.loops_);
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +00001047 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I){
1048 LiveInterval &li = **I;
Jakob Stoklund Olesen9db3ea42010-08-10 18:37:40 +00001049 vrai.CalculateRegClass(li.reg);
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +00001050 vrai.CalculateWeightAndHint(li);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +00001051 DEBUG(dbgs() << " new interval " << mri_.getRegClass(li.reg)->getName()
1052 << ":" << li << '\n');
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +00001053 }
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001054}
1055
1056
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +00001057//===----------------------------------------------------------------------===//
1058// Loop Splitting
1059//===----------------------------------------------------------------------===//
1060
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +00001061void SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001062 SplitAnalysis::LoopBlocks Blocks;
1063 sa_.getLoopBlocks(Loop, Blocks);
1064
Jakob Stoklund Olesen452a9fd2010-10-07 18:47:07 +00001065 DEBUG({
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +00001066 dbgs() << " splitAround"; sa_.print(Blocks, dbgs()); dbgs() << '\n';
Jakob Stoklund Olesen452a9fd2010-10-07 18:47:07 +00001067 });
1068
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001069 // Break critical edges as needed.
1070 SplitAnalysis::BlockPtrSet CriticalExits;
1071 sa_.getCriticalExits(Blocks, CriticalExits);
1072 assert(CriticalExits.empty() && "Cannot break critical exits yet");
1073
Jakob Stoklund Olesenc95c1462010-10-27 00:39:07 +00001074 // Get critical predecessors so computeRemainder can deal with them.
1075 sa_.getCriticalPreds(Blocks, criticalPreds_);
1076
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001077 // Create new live interval for the loop.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +00001078 openIntv();
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001079
Jakob Stoklund Olesendfe3b6d2010-12-18 01:06:19 +00001080 // Insert copies in the predecessors if live-in to the header.
1081 if (lis_.isLiveInToMBB(edit_.getParent(), Loop->getHeader())) {
1082 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
1083 E = Blocks.Preds.end(); I != E; ++I) {
1084 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
1085 enterIntvAtEnd(MBB);
1086 }
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001087 }
1088
1089 // Switch all loop blocks.
1090 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
1091 E = Blocks.Loop.end(); I != E; ++I)
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +00001092 useIntv(**I);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001093
1094 // Insert back copies in the exit blocks.
1095 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
1096 E = Blocks.Exits.end(); I != E; ++I) {
1097 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +00001098 leaveIntvAtTop(MBB);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001099 }
1100
1101 // Done.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +00001102 closeIntv();
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +00001103 finish();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +00001104}
1105
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001106
1107//===----------------------------------------------------------------------===//
1108// Single Block Splitting
1109//===----------------------------------------------------------------------===//
1110
Jakob Stoklund Olesen2bfb3242010-10-22 22:48:56 +00001111/// getMultiUseBlocks - if curli has more than one use in a basic block, it
1112/// may be an advantage to split curli for the duration of the block.
1113bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
1114 // If curli is local to one block, there is no point to splitting it.
1115 if (usingBlocks_.size() <= 1)
1116 return false;
1117 // Add blocks with multiple uses.
1118 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
1119 I != E; ++I)
1120 switch (I->second) {
1121 case 0:
1122 case 1:
1123 continue;
1124 case 2: {
1125 // When there are only two uses and curli is both live in and live out,
1126 // we don't really win anything by isolating the block since we would be
1127 // inserting two copies.
1128 // The remaing register would still have two uses in the block. (Unless it
1129 // separates into disconnected components).
1130 if (lis_.isLiveInToMBB(*curli_, I->first) &&
1131 lis_.isLiveOutOfMBB(*curli_, I->first))
1132 continue;
1133 } // Fall through.
1134 default:
1135 Blocks.insert(I->first);
1136 }
1137 return !Blocks.empty();
1138}
1139
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001140/// splitSingleBlocks - Split curli into a separate live interval inside each
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +00001141/// basic block in Blocks.
1142void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +00001143 DEBUG(dbgs() << " splitSingleBlocks for " << Blocks.size() << " blocks.\n");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001144 // Determine the first and last instruction using curli in each block.
1145 typedef std::pair<SlotIndex,SlotIndex> IndexPair;
1146 typedef DenseMap<const MachineBasicBlock*,IndexPair> IndexPairMap;
1147 IndexPairMap MBBRange;
1148 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1149 E = sa_.usingInstrs_.end(); I != E; ++I) {
1150 const MachineBasicBlock *MBB = (*I)->getParent();
1151 if (!Blocks.count(MBB))
1152 continue;
1153 SlotIndex Idx = lis_.getInstructionIndex(*I);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +00001154 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '\t' << Idx << '\t' << **I);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001155 IndexPair &IP = MBBRange[MBB];
1156 if (!IP.first.isValid() || Idx < IP.first)
1157 IP.first = Idx;
1158 if (!IP.second.isValid() || Idx > IP.second)
1159 IP.second = Idx;
1160 }
1161
1162 // Create a new interval for each block.
1163 for (SplitAnalysis::BlockPtrSet::const_iterator I = Blocks.begin(),
1164 E = Blocks.end(); I != E; ++I) {
1165 IndexPair &IP = MBBRange[*I];
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +00001166 DEBUG(dbgs() << " splitting for BB#" << (*I)->getNumber() << ": ["
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001167 << IP.first << ';' << IP.second << ")\n");
1168 assert(IP.first.isValid() && IP.second.isValid());
1169
1170 openIntv();
1171 enterIntvBefore(IP.first);
1172 useIntv(IP.first.getBaseIndex(), IP.second.getBoundaryIndex());
1173 leaveIntvAfter(IP.second);
1174 closeIntv();
1175 }
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +00001176 finish();
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001177}
1178
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001179
1180//===----------------------------------------------------------------------===//
1181// Sub Block Splitting
1182//===----------------------------------------------------------------------===//
1183
1184/// getBlockForInsideSplit - If curli is contained inside a single basic block,
1185/// and it wou pay to subdivide the interval inside that block, return it.
1186/// Otherwise return NULL. The returned block can be passed to
1187/// SplitEditor::splitInsideBlock.
1188const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
1189 // The interval must be exclusive to one block.
1190 if (usingBlocks_.size() != 1)
1191 return 0;
1192 // Don't to this for less than 4 instructions. We want to be sure that
1193 // splitting actually reduces the instruction count per interval.
1194 if (usingInstrs_.size() < 4)
1195 return 0;
1196 return usingBlocks_.begin()->first;
1197}
1198
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +00001199/// splitInsideBlock - Split curli into multiple intervals inside MBB.
1200void SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001201 SmallVector<SlotIndex, 32> Uses;
1202 Uses.reserve(sa_.usingInstrs_.size());
1203 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1204 E = sa_.usingInstrs_.end(); I != E; ++I)
1205 if ((*I)->getParent() == MBB)
1206 Uses.push_back(lis_.getInstructionIndex(*I));
1207 DEBUG(dbgs() << " splitInsideBlock BB#" << MBB->getNumber() << " for "
1208 << Uses.size() << " instructions.\n");
1209 assert(Uses.size() >= 3 && "Need at least 3 instructions");
1210 array_pod_sort(Uses.begin(), Uses.end());
1211
1212 // Simple algorithm: Find the largest gap between uses as determined by slot
1213 // indices. Create new intervals for instructions before the gap and after the
1214 // gap.
1215 unsigned bestPos = 0;
1216 int bestGap = 0;
1217 DEBUG(dbgs() << " dist (" << Uses[0]);
1218 for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
1219 int g = Uses[i-1].distance(Uses[i]);
1220 DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
1221 if (g > bestGap)
1222 bestPos = i, bestGap = g;
1223 }
1224 DEBUG(dbgs() << "), best: -" << bestGap << "-\n");
1225
1226 // bestPos points to the first use after the best gap.
1227 assert(bestPos > 0 && "Invalid gap");
1228
1229 // FIXME: Don't create intervals for low densities.
1230
1231 // First interval before the gap. Don't create single-instr intervals.
1232 if (bestPos > 1) {
1233 openIntv();
1234 enterIntvBefore(Uses.front());
1235 useIntv(Uses.front().getBaseIndex(), Uses[bestPos-1].getBoundaryIndex());
1236 leaveIntvAfter(Uses[bestPos-1]);
1237 closeIntv();
1238 }
1239
1240 // Second interval after the gap.
1241 if (bestPos < Uses.size()-1) {
1242 openIntv();
1243 enterIntvBefore(Uses[bestPos]);
1244 useIntv(Uses[bestPos].getBaseIndex(), Uses.back().getBoundaryIndex());
1245 leaveIntvAfter(Uses.back());
1246 closeIntv();
1247 }
1248
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +00001249 finish();
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001250}