blob: 7ed9089ecd0267aff4f2bf4673cfae125c48fc28 [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() {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000051 UseSlots.clear();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000052 usingInstrs_.clear();
53 usingBlocks_.clear();
54 usingLoops_.clear();
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +000055 curli_ = 0;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000056}
57
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000058bool SplitAnalysis::canAnalyzeBranch(const MachineBasicBlock *MBB) {
59 MachineBasicBlock *T, *F;
60 SmallVector<MachineOperand, 4> Cond;
61 return !tii_.AnalyzeBranch(const_cast<MachineBasicBlock&>(*MBB), T, F, Cond);
62}
63
Jakob Stoklund Olesenabff2802010-07-20 16:12:37 +000064/// analyzeUses - Count instructions, basic blocks, and loops using curli.
65void SplitAnalysis::analyzeUses() {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000066 const MachineRegisterInfo &MRI = mf_.getRegInfo();
67 for (MachineRegisterInfo::reg_iterator I = MRI.reg_begin(curli_->reg);
68 MachineInstr *MI = I.skipInstruction();) {
69 if (MI->isDebugValue() || !usingInstrs_.insert(MI))
70 continue;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000071 UseSlots.push_back(lis_.getInstructionIndex(MI).getDefIndex());
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000072 MachineBasicBlock *MBB = MI->getParent();
73 if (usingBlocks_[MBB]++)
74 continue;
Jakob Stoklund Olesen9b90d7e2010-10-05 23:10:12 +000075 for (MachineLoop *Loop = loops_.getLoopFor(MBB); Loop;
76 Loop = Loop->getParentLoop())
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +000077 usingLoops_[Loop]++;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000078 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000079 array_pod_sort(UseSlots.begin(), UseSlots.end());
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +000080 DEBUG(dbgs() << " counted "
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000081 << usingInstrs_.size() << " instrs, "
82 << usingBlocks_.size() << " blocks, "
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +000083 << usingLoops_.size() << " loops.\n");
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000084}
85
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +000086void SplitAnalysis::print(const BlockPtrSet &B, raw_ostream &OS) const {
87 for (BlockPtrSet::const_iterator I = B.begin(), E = B.end(); I != E; ++I) {
88 unsigned count = usingBlocks_.lookup(*I);
89 OS << " BB#" << (*I)->getNumber();
90 if (count)
91 OS << '(' << count << ')';
92 }
93}
94
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +000095// Get three sets of basic blocks surrounding a loop: Blocks inside the loop,
96// predecessor blocks, and exit blocks.
97void SplitAnalysis::getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks) {
98 Blocks.clear();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +000099
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000100 // Blocks in the loop.
101 Blocks.Loop.insert(Loop->block_begin(), Loop->block_end());
102
103 // Predecessor blocks.
104 const MachineBasicBlock *Header = Loop->getHeader();
105 for (MachineBasicBlock::const_pred_iterator I = Header->pred_begin(),
106 E = Header->pred_end(); I != E; ++I)
107 if (!Blocks.Loop.count(*I))
108 Blocks.Preds.insert(*I);
109
110 // Exit blocks.
111 for (MachineLoop::block_iterator I = Loop->block_begin(),
112 E = Loop->block_end(); I != E; ++I) {
113 const MachineBasicBlock *MBB = *I;
114 for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
115 SE = MBB->succ_end(); SI != SE; ++SI)
116 if (!Blocks.Loop.count(*SI))
117 Blocks.Exits.insert(*SI);
118 }
119}
120
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000121void SplitAnalysis::print(const LoopBlocks &B, raw_ostream &OS) const {
122 OS << "Loop:";
123 print(B.Loop, OS);
124 OS << ", preds:";
125 print(B.Preds, OS);
126 OS << ", exits:";
127 print(B.Exits, OS);
128}
129
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000130/// analyzeLoopPeripheralUse - Return an enum describing how curli_ is used in
131/// and around the Loop.
132SplitAnalysis::LoopPeripheralUse SplitAnalysis::
133analyzeLoopPeripheralUse(const SplitAnalysis::LoopBlocks &Blocks) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000134 LoopPeripheralUse use = ContainedInLoop;
135 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
136 I != E; ++I) {
137 const MachineBasicBlock *MBB = I->first;
138 // Is this a peripheral block?
139 if (use < MultiPeripheral &&
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000140 (Blocks.Preds.count(MBB) || Blocks.Exits.count(MBB))) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000141 if (I->second > 1) use = MultiPeripheral;
142 else use = SinglePeripheral;
143 continue;
144 }
145 // Is it a loop block?
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000146 if (Blocks.Loop.count(MBB))
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000147 continue;
148 // It must be an unrelated block.
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000149 DEBUG(dbgs() << ", outside: BB#" << MBB->getNumber());
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000150 return OutsideLoop;
151 }
152 return use;
153}
154
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000155/// getCriticalExits - It may be necessary to partially break critical edges
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000156/// leaving the loop if an exit block has predecessors from outside the loop
157/// periphery.
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000158void SplitAnalysis::getCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
159 BlockPtrSet &CriticalExits) {
160 CriticalExits.clear();
161
Jakob Stoklund Olesen0960a652010-10-27 00:39:05 +0000162 // A critical exit block has curli live-in, and has a predecessor that is not
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000163 // in the loop nor a loop predecessor. For such an exit block, the edges
164 // carrying the new variable must be moved to a new pre-exit block.
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000165 for (BlockPtrSet::iterator I = Blocks.Exits.begin(), E = Blocks.Exits.end();
166 I != E; ++I) {
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000167 const MachineBasicBlock *Exit = *I;
168 // A single-predecessor exit block is definitely not a critical edge.
169 if (Exit->pred_size() == 1)
170 continue;
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000171 // This exit may not have curli live in at all. No need to split.
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000172 if (!lis_.isLiveInToMBB(*curli_, Exit))
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000173 continue;
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000174 // Does this exit block have a predecessor that is not a loop block or loop
175 // predecessor?
176 for (MachineBasicBlock::const_pred_iterator PI = Exit->pred_begin(),
177 PE = Exit->pred_end(); PI != PE; ++PI) {
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000178 const MachineBasicBlock *Pred = *PI;
179 if (Blocks.Loop.count(Pred) || Blocks.Preds.count(Pred))
180 continue;
181 // This is a critical exit block, and we need to split the exit edge.
Jakob Stoklund Olesen2c1442e2010-10-22 20:28:23 +0000182 CriticalExits.insert(Exit);
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000183 break;
184 }
185 }
186}
187
Jakob Stoklund Olesen0960a652010-10-27 00:39:05 +0000188void SplitAnalysis::getCriticalPreds(const SplitAnalysis::LoopBlocks &Blocks,
189 BlockPtrSet &CriticalPreds) {
190 CriticalPreds.clear();
191
192 // A critical predecessor block has curli live-out, and has a successor that
193 // has curli live-in and is not in the loop nor a loop exit block. For such a
194 // predecessor block, we must carry the value in both the 'inside' and
195 // 'outside' registers.
196 for (BlockPtrSet::iterator I = Blocks.Preds.begin(), E = Blocks.Preds.end();
197 I != E; ++I) {
198 const MachineBasicBlock *Pred = *I;
199 // Definitely not a critical edge.
200 if (Pred->succ_size() == 1)
201 continue;
202 // This block may not have curli live out at all if there is a PHI.
203 if (!lis_.isLiveOutOfMBB(*curli_, Pred))
204 continue;
205 // Does this block have a successor outside the loop?
206 for (MachineBasicBlock::const_pred_iterator SI = Pred->succ_begin(),
207 SE = Pred->succ_end(); SI != SE; ++SI) {
208 const MachineBasicBlock *Succ = *SI;
209 if (Blocks.Loop.count(Succ) || Blocks.Exits.count(Succ))
210 continue;
211 if (!lis_.isLiveInToMBB(*curli_, Succ))
212 continue;
213 // This is a critical predecessor block.
214 CriticalPreds.insert(Pred);
215 break;
216 }
217 }
218}
219
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000220/// canSplitCriticalExits - Return true if it is possible to insert new exit
221/// blocks before the blocks in CriticalExits.
222bool
223SplitAnalysis::canSplitCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
224 BlockPtrSet &CriticalExits) {
225 // If we don't allow critical edge splitting, require no critical exits.
226 if (!AllowSplit)
227 return CriticalExits.empty();
228
229 for (BlockPtrSet::iterator I = CriticalExits.begin(), E = CriticalExits.end();
230 I != E; ++I) {
231 const MachineBasicBlock *Succ = *I;
232 // We want to insert a new pre-exit MBB before Succ, and change all the
233 // in-loop blocks to branch to the pre-exit instead of Succ.
234 // Check that all the in-loop predecessors can be changed.
235 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
236 PE = Succ->pred_end(); PI != PE; ++PI) {
237 const MachineBasicBlock *Pred = *PI;
238 // The external predecessors won't be altered.
239 if (!Blocks.Loop.count(Pred) && !Blocks.Preds.count(Pred))
240 continue;
241 if (!canAnalyzeBranch(Pred))
242 return false;
243 }
244
245 // If Succ's layout predecessor falls through, that too must be analyzable.
246 // We need to insert the pre-exit block in the gap.
247 MachineFunction::const_iterator MFI = Succ;
248 if (MFI == mf_.begin())
249 continue;
250 if (!canAnalyzeBranch(--MFI))
251 return false;
252 }
253 // No problems found.
254 return true;
255}
256
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000257void SplitAnalysis::analyze(const LiveInterval *li) {
258 clear();
259 curli_ = li;
Jakob Stoklund Olesenabff2802010-07-20 16:12:37 +0000260 analyzeUses();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000261}
262
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000263void SplitAnalysis::getSplitLoops(LoopPtrSet &Loops) {
264 assert(curli_ && "Call analyze() before getSplitLoops");
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000265 if (usingLoops_.empty())
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000266 return;
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000267
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000268 LoopBlocks Blocks;
269 BlockPtrSet CriticalExits;
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000270
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000271 // We split around loops where curli is used outside the periphery.
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000272 for (LoopCountMap::const_iterator I = usingLoops_.begin(),
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000273 E = usingLoops_.end(); I != E; ++I) {
Jakob Stoklund Olesen2dee7a52010-08-12 23:02:55 +0000274 const MachineLoop *Loop = I->first;
275 getLoopBlocks(Loop, Blocks);
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000276 DEBUG({ dbgs() << " "; print(Blocks, dbgs()); });
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000277
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000278 switch(analyzeLoopPeripheralUse(Blocks)) {
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000279 case OutsideLoop:
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000280 break;
281 case MultiPeripheral:
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000282 // FIXME: We could split a live range with multiple uses in a peripheral
283 // block and still make progress. However, it is possible that splitting
284 // another live range will insert copies into a peripheral block, and
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000285 // there is a small chance we can enter an infinite loop, inserting copies
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000286 // forever.
287 // For safety, stick to splitting live ranges with uses outside the
288 // periphery.
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000289 DEBUG(dbgs() << ": multiple peripheral uses");
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000290 break;
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000291 case ContainedInLoop:
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000292 DEBUG(dbgs() << ": fully contained\n");
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000293 continue;
294 case SinglePeripheral:
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000295 DEBUG(dbgs() << ": single peripheral use\n");
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000296 continue;
297 }
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000298 // Will it be possible to split around this loop?
299 getCriticalExits(Blocks, CriticalExits);
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +0000300 DEBUG(dbgs() << ": " << CriticalExits.size() << " critical exits\n");
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000301 if (!canSplitCriticalExits(Blocks, CriticalExits))
302 continue;
303 // This is a possible split.
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000304 Loops.insert(Loop);
Jakob Stoklund Olesen6a0dc072010-07-20 21:46:58 +0000305 }
306
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000307 DEBUG(dbgs() << " getSplitLoops found " << Loops.size()
Jakob Stoklund Olesenab00e9f2010-10-14 18:26:45 +0000308 << " candidate loops.\n");
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000309}
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000310
Jakob Stoklund Olesen521a4532010-12-15 17:41:19 +0000311const MachineLoop *SplitAnalysis::getBestSplitLoop() {
312 LoopPtrSet Loops;
313 getSplitLoops(Loops);
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000314 if (Loops.empty())
315 return 0;
316
317 // Pick the earliest loop.
318 // FIXME: Are there other heuristics to consider?
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000319 const MachineLoop *Best = 0;
320 SlotIndex BestIdx;
321 for (LoopPtrSet::const_iterator I = Loops.begin(), E = Loops.end(); I != E;
322 ++I) {
323 SlotIndex Idx = lis_.getMBBStartIdx((*I)->getHeader());
324 if (!Best || Idx < BestIdx)
325 Best = *I, BestIdx = Idx;
326 }
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000327 DEBUG(dbgs() << " getBestSplitLoop found " << *Best);
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +0000328 return Best;
329}
330
Jakob Stoklund Olesen697483a2010-12-15 17:49:52 +0000331/// isBypassLoop - Return true if curli is live through Loop and has no uses
332/// inside the loop. Bypass loops are candidates for splitting because it can
333/// prevent interference inside the loop.
334bool SplitAnalysis::isBypassLoop(const MachineLoop *Loop) {
335 // If curli is live into the loop header and there are no uses in the loop, it
336 // must be live in the entire loop and live on at least one exiting edge.
337 return !usingLoops_.count(Loop) &&
338 lis_.isLiveInToMBB(*curli_, Loop->getHeader());
339}
340
341/// getBypassLoops - Get all the maximal bypass loops. These are the bypass
342/// loops whose parent is not a bypass loop.
343void SplitAnalysis::getBypassLoops(LoopPtrSet &BypassLoops) {
344 SmallVector<MachineLoop*, 8> Todo(loops_.begin(), loops_.end());
Jakob Stoklund Olesen62032952010-12-15 18:07:48 +0000345 while (!Todo.empty()) {
Jakob Stoklund Olesen697483a2010-12-15 17:49:52 +0000346 MachineLoop *Loop = Todo.pop_back_val();
347 if (!usingLoops_.count(Loop)) {
348 // This is either a bypass loop or completely irrelevant.
349 if (lis_.isLiveInToMBB(*curli_, Loop->getHeader()))
350 BypassLoops.insert(Loop);
351 // Either way, skip the child loops.
352 continue;
353 }
354
355 // The child loops may be bypass loops.
356 Todo.append(Loop->begin(), Loop->end());
357 }
358}
359
360
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000361//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000362// LiveIntervalMap
363//===----------------------------------------------------------------------===//
364
Jakob Stoklund Olesenb3e96812010-09-13 21:29:45 +0000365// Work around the fact that the std::pair constructors are broken for pointer
366// pairs in some implementations. makeVV(x, 0) works.
367static inline std::pair<const VNInfo*, VNInfo*>
368makeVV(const VNInfo *a, VNInfo *b) {
369 return std::make_pair(a, b);
370}
371
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000372void LiveIntervalMap::reset(LiveInterval *li) {
373 li_ = li;
374 valueMap_.clear();
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000375 liveOutCache_.clear();
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000376}
377
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000378bool LiveIntervalMap::isComplexMapped(const VNInfo *ParentVNI) const {
379 ValueMap::const_iterator i = valueMap_.find(ParentVNI);
380 return i != valueMap_.end() && i->second == 0;
381}
382
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000383// defValue - Introduce a li_ def for ParentVNI that could be later than
384// ParentVNI->def.
385VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000386 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000387 assert(ParentVNI && "Mapping NULL value");
388 assert(Idx.isValid() && "Invalid SlotIndex");
389 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
390
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000391 // Create a new value.
Lang Hames6e2968c2010-09-25 12:04:16 +0000392 VNInfo *VNI = li_->getNextValue(Idx, 0, lis_.getVNInfoAllocator());
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000393
Jakob Stoklund Olesen79c02622010-10-26 22:36:02 +0000394 // Preserve the PHIDef bit.
395 if (ParentVNI->isPHIDef() && Idx == ParentVNI->def)
396 VNI->setIsPHIDef(true);
397
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000398 // Use insert for lookup, so we can add missing values with a second lookup.
399 std::pair<ValueMap::iterator,bool> InsP =
400 valueMap_.insert(makeVV(ParentVNI, Idx == ParentVNI->def ? VNI : 0));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000401
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000402 // This is now a complex def. Mark with a NULL in valueMap.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000403 if (!InsP.second)
404 InsP.first->second = 0;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000405
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000406 return VNI;
407}
408
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000409
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000410// mapValue - Find the mapped value for ParentVNI at Idx.
411// Potentially create phi-def values.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000412VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx,
413 bool *simple) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000414 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000415 assert(ParentVNI && "Mapping NULL value");
416 assert(Idx.isValid() && "Invalid SlotIndex");
417 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
418
419 // Use insert for lookup, so we can add missing values with a second lookup.
420 std::pair<ValueMap::iterator,bool> InsP =
Jakob Stoklund Olesenb3e96812010-09-13 21:29:45 +0000421 valueMap_.insert(makeVV(ParentVNI, 0));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000422
423 // This was an unknown value. Create a simple mapping.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000424 if (InsP.second) {
425 if (simple) *simple = true;
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000426 return InsP.first->second = li_->createValueCopy(ParentVNI,
427 lis_.getVNInfoAllocator());
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000428 }
429
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000430 // This was a simple mapped value.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000431 if (InsP.first->second) {
432 if (simple) *simple = true;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000433 return InsP.first->second;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000434 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000435
436 // This is a complex mapped value. There may be multiple defs, and we may need
437 // to create phi-defs.
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000438 if (simple) *simple = false;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000439 MachineBasicBlock *IdxMBB = lis_.getMBBFromIndex(Idx);
440 assert(IdxMBB && "No MBB at Idx");
441
442 // Is there a def in the same MBB we can extend?
443 if (VNInfo *VNI = extendTo(IdxMBB, Idx))
444 return VNI;
445
446 // Now for the fun part. We know that ParentVNI potentially has multiple defs,
447 // and we may need to create even more phi-defs to preserve VNInfo SSA form.
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000448 // Perform a search for all predecessor blocks where we know the dominating
449 // VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
450 DEBUG(dbgs() << "\n Reaching defs for BB#" << IdxMBB->getNumber()
451 << " at " << Idx << " in " << *li_ << '\n');
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000452
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000453 // Blocks where li_ should be live-in.
454 SmallVector<MachineDomTreeNode*, 16> LiveIn;
455 LiveIn.push_back(mdt_[IdxMBB]);
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000456
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000457 // Using liveOutCache_ as a visited set, perform a BFS for all reaching defs.
458 for (unsigned i = 0; i != LiveIn.size(); ++i) {
459 MachineBasicBlock *MBB = LiveIn[i]->getBlock();
460 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
461 PE = MBB->pred_end(); PI != PE; ++PI) {
462 MachineBasicBlock *Pred = *PI;
463 // Is this a known live-out block?
464 std::pair<LiveOutMap::iterator,bool> LOIP =
465 liveOutCache_.insert(std::make_pair(Pred, LiveOutPair()));
466 // Yes, we have been here before.
467 if (!LOIP.second) {
Benjamin Kramer8a8e26f2010-10-29 17:40:05 +0000468 DEBUG(if (VNInfo *VNI = LOIP.first->second.first)
469 dbgs() << " known valno #" << VNI->id
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000470 << " at BB#" << Pred->getNumber() << '\n');
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000471 continue;
472 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000473
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000474 // Does Pred provide a live-out value?
475 SlotIndex Last = lis_.getMBBEndIdx(Pred).getPrevSlot();
476 if (VNInfo *VNI = extendTo(Pred, Last)) {
477 MachineBasicBlock *DefMBB = lis_.getMBBFromIndex(VNI->def);
478 DEBUG(dbgs() << " found valno #" << VNI->id
Jakob Stoklund Olesenc94fcb12010-10-29 17:37:25 +0000479 << " from BB#" << DefMBB->getNumber()
480 << " at BB#" << Pred->getNumber() << '\n');
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000481 LiveOutPair &LOP = LOIP.first->second;
482 LOP.first = VNI;
Benjamin Kramer8a8e26f2010-10-29 17:40:05 +0000483 LOP.second = mdt_[DefMBB];
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000484 continue;
485 }
486 // No, we need a live-in value for Pred as well
487 if (Pred != IdxMBB)
488 LiveIn.push_back(mdt_[Pred]);
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000489 }
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000490 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000491
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000492 // We may need to add phi-def values to preserve the SSA form.
493 // This is essentially the same iterative algorithm that SSAUpdater uses,
494 // except we already have a dominator tree, so we don't have to recompute it.
495 VNInfo *IdxVNI = 0;
496 unsigned Changes;
497 do {
498 Changes = 0;
499 DEBUG(dbgs() << " Iterating over " << LiveIn.size() << " blocks.\n");
500 // Propagate live-out values down the dominator tree, inserting phi-defs when
501 // necessary. Since LiveIn was created by a BFS, going backwards makes it more
502 // likely for us to visit immediate dominators before their children.
503 for (unsigned i = LiveIn.size(); i; --i) {
504 MachineDomTreeNode *Node = LiveIn[i-1];
505 MachineBasicBlock *MBB = Node->getBlock();
506 MachineDomTreeNode *IDom = Node->getIDom();
507 LiveOutPair IDomValue;
508 // We need a live-in value to a block with no immediate dominator?
509 // This is probably an unreachable block that has survived somehow.
510 bool needPHI = !IDom;
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000511
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000512 // Get the IDom live-out value.
513 if (!needPHI) {
514 LiveOutMap::iterator I = liveOutCache_.find(IDom->getBlock());
515 if (I != liveOutCache_.end())
516 IDomValue = I->second;
517 else
518 // If IDom is outside our set of live-out blocks, there must be new
519 // defs, and we need a phi-def here.
520 needPHI = true;
521 }
Jakob Stoklund Olesen984a7fc2010-10-05 20:36:28 +0000522
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000523 // IDom dominates all of our predecessors, but it may not be the immediate
524 // dominator. Check if any of them have live-out values that are properly
525 // dominated by IDom. If so, we need a phi-def here.
526 if (!needPHI) {
527 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
528 PE = MBB->pred_end(); PI != PE; ++PI) {
529 LiveOutPair Value = liveOutCache_[*PI];
530 if (!Value.first || Value.first == IDomValue.first)
531 continue;
532 // This predecessor is carrying something other than IDomValue.
533 // It could be because IDomValue hasn't propagated yet, or it could be
534 // because MBB is in the dominance frontier of that value.
535 if (mdt_.dominates(IDom, Value.second)) {
536 needPHI = true;
537 break;
538 }
539 }
540 }
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000541
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000542 // Create a phi-def if required.
543 if (needPHI) {
544 ++Changes;
545 SlotIndex Start = lis_.getMBBStartIdx(MBB);
546 VNInfo *VNI = li_->getNextValue(Start, 0, lis_.getVNInfoAllocator());
547 VNI->setIsPHIDef(true);
548 DEBUG(dbgs() << " - BB#" << MBB->getNumber()
549 << " phi-def #" << VNI->id << " at " << Start << '\n');
550 // We no longer need li_ to be live-in.
551 LiveIn.erase(LiveIn.begin()+(i-1));
552 // Blocks in LiveIn are either IdxMBB, or have a value live-through.
553 if (MBB == IdxMBB)
554 IdxVNI = VNI;
555 // Check if we need to update live-out info.
556 LiveOutMap::iterator I = liveOutCache_.find(MBB);
557 if (I == liveOutCache_.end() || I->second.second == Node) {
558 // We already have a live-out defined in MBB, so this must be IdxMBB.
559 assert(MBB == IdxMBB && "Adding phi-def to known live-out");
560 li_->addRange(LiveRange(Start, Idx.getNextSlot(), VNI));
561 } else {
562 // This phi-def is also live-out, so color the whole block.
563 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
564 I->second = LiveOutPair(VNI, Node);
565 }
566 } else if (IDomValue.first) {
Jakob Stoklund Olesenc94fcb12010-10-29 17:37:25 +0000567 // No phi-def here. Remember incoming value for IdxMBB.
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000568 if (MBB == IdxMBB)
569 IdxVNI = IDomValue.first;
Jakob Stoklund Olesenc94fcb12010-10-29 17:37:25 +0000570 // Propagate IDomValue if needed:
571 // MBB is live-out and doesn't define its own value.
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000572 LiveOutMap::iterator I = liveOutCache_.find(MBB);
Jakob Stoklund Olesenc94fcb12010-10-29 17:37:25 +0000573 if (I != liveOutCache_.end() && I->second.second != Node &&
574 I->second.first != IDomValue.first) {
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000575 ++Changes;
576 I->second = IDomValue;
577 DEBUG(dbgs() << " - BB#" << MBB->getNumber()
578 << " idom valno #" << IDomValue.first->id
579 << " from BB#" << IDom->getBlock()->getNumber() << '\n');
580 }
Jakob Stoklund Olesenff3ae862010-08-18 20:29:53 +0000581 }
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000582 }
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000583 DEBUG(dbgs() << " - made " << Changes << " changes.\n");
584 } while (Changes);
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000585
586 assert(IdxVNI && "Didn't find value for Idx");
Jakob Stoklund Olesene1dde7b2010-10-28 20:34:52 +0000587
588#ifndef NDEBUG
589 // Check the liveOutCache_ invariants.
590 for (LiveOutMap::iterator I = liveOutCache_.begin(), E = liveOutCache_.end();
591 I != E; ++I) {
592 assert(I->first && "Null MBB entry in cache");
593 assert(I->second.first && "Null VNInfo in cache");
594 assert(I->second.second && "Null DomTreeNode in cache");
595 if (I->second.second->getBlock() == I->first)
596 continue;
597 for (MachineBasicBlock::pred_iterator PI = I->first->pred_begin(),
598 PE = I->first->pred_end(); PI != PE; ++PI)
599 assert(liveOutCache_.lookup(*PI) == I->second && "Bad invariant");
600 }
601#endif
602
603 // Since we went through the trouble of a full BFS visiting all reaching defs,
604 // the values in LiveIn are now accurate. No more phi-defs are needed
605 // for these blocks, so we can color the live ranges.
606 // This makes the next mapValue call much faster.
607 for (unsigned i = 0, e = LiveIn.size(); i != e; ++i) {
608 MachineBasicBlock *MBB = LiveIn[i]->getBlock();
609 SlotIndex Start = lis_.getMBBStartIdx(MBB);
610 if (MBB == IdxMBB) {
611 li_->addRange(LiveRange(Start, Idx.getNextSlot(), IdxVNI));
612 continue;
613 }
614 // Anything in LiveIn other than IdxMBB is live-through.
615 VNInfo *VNI = liveOutCache_.lookup(MBB).first;
616 assert(VNI && "Missing block value");
617 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
618 }
619
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000620 return IdxVNI;
621}
622
623// extendTo - Find the last li_ value defined in MBB at or before Idx. The
624// parentli_ is assumed to be live at Idx. Extend the live range to Idx.
625// Return the found VNInfo, or NULL.
Jakob Stoklund Olesenc95c1462010-10-27 00:39:07 +0000626VNInfo *LiveIntervalMap::extendTo(const MachineBasicBlock *MBB, SlotIndex Idx) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000627 assert(li_ && "call reset first");
628 LiveInterval::iterator I = std::upper_bound(li_->begin(), li_->end(), Idx);
629 if (I == li_->begin())
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000630 return 0;
631 --I;
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000632 if (I->end <= lis_.getMBBStartIdx(MBB))
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000633 return 0;
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000634 if (I->end <= Idx)
635 I->end = Idx.getNextSlot();
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000636 return I->valno;
637}
638
639// addSimpleRange - Add a simple range from parentli_ to li_.
640// ParentVNI must be live in the [Start;End) interval.
641void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End,
642 const VNInfo *ParentVNI) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000643 assert(li_ && "call reset first");
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000644 bool simple;
645 VNInfo *VNI = mapValue(ParentVNI, Start, &simple);
646 // A simple mapping is easy.
647 if (simple) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000648 li_->addRange(LiveRange(Start, End, VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000649 return;
650 }
651
652 // ParentVNI is a complex value. We must map per MBB.
653 MachineFunction::iterator MBB = lis_.getMBBFromIndex(Start);
Jakob Stoklund Olesendbc36092010-10-05 22:19:29 +0000654 MachineFunction::iterator MBBE = lis_.getMBBFromIndex(End.getPrevSlot());
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000655
656 if (MBB == MBBE) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000657 li_->addRange(LiveRange(Start, End, VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000658 return;
659 }
660
661 // First block.
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000662 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000663
664 // Run sequence of full blocks.
665 for (++MBB; MBB != MBBE; ++MBB) {
666 Start = lis_.getMBBStartIdx(MBB);
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000667 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB),
668 mapValue(ParentVNI, Start)));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000669 }
670
671 // Final block.
672 Start = lis_.getMBBStartIdx(MBB);
673 if (Start != End)
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000674 li_->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start)));
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000675}
676
677/// addRange - Add live ranges to li_ where [Start;End) intersects parentli_.
678/// All needed values whose def is not inside [Start;End) must be defined
679/// beforehand so mapValue will work.
680void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) {
Jakob Stoklund Olesen9ca2aeb2010-09-13 23:29:09 +0000681 assert(li_ && "call reset first");
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000682 LiveInterval::const_iterator B = parentli_.begin(), E = parentli_.end();
683 LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
684
685 // Check if --I begins before Start and overlaps.
686 if (I != B) {
687 --I;
688 if (I->end > Start)
689 addSimpleRange(Start, std::min(End, I->end), I->valno);
690 ++I;
691 }
692
693 // The remaining ranges begin after Start.
694 for (;I != E && I->start < End; ++I)
695 addSimpleRange(I->start, std::min(End, I->end), I->valno);
696}
697
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000698
Jakob Stoklund Olesen1407c842010-08-18 19:00:08 +0000699//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000700// Split Editor
701//===----------------------------------------------------------------------===//
702
703/// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
Jakob Stoklund Olesend68f4582010-10-28 20:34:50 +0000704SplitEditor::SplitEditor(SplitAnalysis &sa,
705 LiveIntervals &lis,
706 VirtRegMap &vrm,
707 MachineDominatorTree &mdt,
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000708 LiveRangeEdit &edit)
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000709 : sa_(sa), lis_(lis), vrm_(vrm),
710 mri_(vrm.getMachineFunction().getRegInfo()),
711 tii_(*vrm.getMachineFunction().getTarget().getInstrInfo()),
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000712 tri_(*vrm.getMachineFunction().getTarget().getRegisterInfo()),
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000713 edit_(edit),
Jakob Stoklund Olesend68f4582010-10-28 20:34:50 +0000714 dupli_(lis_, mdt, edit.getParent()),
715 openli_(lis_, mdt, edit.getParent())
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000716{
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000717 // We don't need an AliasAnalysis since we will only be performing
718 // cheap-as-a-copy remats anyway.
719 edit_.anyRematerializable(lis_, tii_, 0);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000720}
721
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000722bool SplitEditor::intervalsLiveAt(SlotIndex Idx) const {
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000723 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I)
724 if (*I != dupli_.getLI() && (*I)->liveAt(Idx))
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000725 return true;
726 return false;
727}
728
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000729VNInfo *SplitEditor::defFromParent(LiveIntervalMap &Reg,
730 VNInfo *ParentVNI,
731 SlotIndex UseIdx,
732 MachineBasicBlock &MBB,
733 MachineBasicBlock::iterator I) {
734 VNInfo *VNI = 0;
735 MachineInstr *CopyMI = 0;
736 SlotIndex Def;
737
738 // Attempt cheap-as-a-copy rematerialization.
739 LiveRangeEdit::Remat RM(ParentVNI);
740 if (edit_.canRematerializeAt(RM, UseIdx, true, lis_)) {
741 Def = edit_.rematerializeAt(MBB, I, Reg.getLI()->reg, RM,
742 lis_, tii_, tri_);
743 } else {
744 // Can't remat, just insert a copy from parent.
745 CopyMI = BuildMI(MBB, I, DebugLoc(), tii_.get(TargetOpcode::COPY),
746 Reg.getLI()->reg).addReg(edit_.getReg());
747 Def = lis_.InsertMachineInstrInMaps(CopyMI).getDefIndex();
748 }
749
750 // Define the value in Reg.
751 VNI = Reg.defValue(ParentVNI, Def);
752 VNI->setCopy(CopyMI);
753
754 // Add minimal liveness for the new value.
755 if (UseIdx < Def)
756 UseIdx = Def;
757 Reg.getLI()->addRange(LiveRange(Def, UseIdx.getNextSlot(), VNI));
758 return VNI;
759}
760
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000761/// Create a new virtual register and live interval.
762void SplitEditor::openIntv() {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000763 assert(!openli_.getLI() && "Previous LI not closed before openIntv");
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000764 if (!dupli_.getLI())
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000765 dupli_.reset(&edit_.create(mri_, lis_, vrm_));
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000766
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000767 openli_.reset(&edit_.create(mri_, lis_, vrm_));
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000768}
769
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000770/// enterIntvBefore - Enter openli before the instruction at Idx. If curli is
771/// not live before Idx, a COPY is not inserted.
772void SplitEditor::enterIntvBefore(SlotIndex Idx) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000773 assert(openli_.getLI() && "openIntv not called before enterIntvBefore");
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000774 Idx = Idx.getUseIndex();
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000775 DEBUG(dbgs() << " enterIntvBefore " << Idx);
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000776 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000777 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000778 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000779 return;
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000780 }
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000781 DEBUG(dbgs() << ": valno " << ParentVNI->id);
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000782 truncatedValues.insert(ParentVNI);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000783 MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
784 assert(MI && "enterIntvBefore called with invalid index");
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000785
786 defFromParent(openli_, ParentVNI, Idx, *MI->getParent(), MI);
787
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000788 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000789}
790
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000791/// enterIntvAtEnd - Enter openli at the end of MBB.
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000792void SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000793 assert(openli_.getLI() && "openIntv not called before enterIntvAtEnd");
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000794 SlotIndex End = lis_.getMBBEndIdx(&MBB).getPrevSlot();
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000795 DEBUG(dbgs() << " enterIntvAtEnd BB#" << MBB.getNumber() << ", " << End);
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000796 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(End);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000797 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000798 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000799 return;
800 }
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000801 DEBUG(dbgs() << ": valno " << ParentVNI->id);
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000802 truncatedValues.insert(ParentVNI);
Jakob Stoklund Olesenb5f327b2010-11-10 23:56:00 +0000803 defFromParent(openli_, ParentVNI, End, MBB, MBB.getFirstTerminator());
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000804 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000805}
806
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000807/// useIntv - indicate that all instructions in MBB should use openli.
808void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
809 useIntv(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB));
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000810}
811
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000812void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000813 assert(openli_.getLI() && "openIntv not called before useIntv");
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000814 openli_.addRange(Start, End);
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000815 DEBUG(dbgs() << " use [" << Start << ';' << End << "): "
816 << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000817}
818
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000819/// leaveIntvAfter - Leave openli after the instruction at Idx.
820void SplitEditor::leaveIntvAfter(SlotIndex Idx) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000821 assert(openli_.getLI() && "openIntv not called before leaveIntvAfter");
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000822 DEBUG(dbgs() << " leaveIntvAfter " << Idx);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000823
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000824 // The interval must be live beyond the instruction at Idx.
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000825 Idx = Idx.getBoundaryIndex();
826 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000827 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000828 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000829 return;
830 }
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000831 DEBUG(dbgs() << ": valno " << ParentVNI->id);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000832
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000833 MachineBasicBlock::iterator MII = lis_.getInstructionFromIndex(Idx);
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000834 VNInfo *VNI = defFromParent(dupli_, ParentVNI, Idx,
835 *MII->getParent(), llvm::next(MII));
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000836
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000837 // Make sure that openli is properly extended from Idx to the new copy.
838 // FIXME: This shouldn't be necessary for remats.
839 openli_.addSimpleRange(Idx, VNI->def, ParentVNI);
840
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000841 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +0000842}
843
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000844/// leaveIntvAtTop - Leave the interval at the top of MBB.
845/// Currently, only one value can leave the interval.
846void SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000847 assert(openli_.getLI() && "openIntv not called before leaveIntvAtTop");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000848 SlotIndex Start = lis_.getMBBStartIdx(&MBB);
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000849 DEBUG(dbgs() << " leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000850
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000851 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Start);
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000852 if (!ParentVNI) {
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000853 DEBUG(dbgs() << ": not live\n");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000854 return;
855 }
856
Jakob Stoklund Olesencfa71342010-11-10 19:31:50 +0000857 VNInfo *VNI = defFromParent(dupli_, ParentVNI, Start, MBB,
858 MBB.SkipPHIsAndLabels(MBB.begin()));
Jakob Stoklund Olesen5eb308b2010-08-06 22:17:33 +0000859
Jakob Stoklund Olesenf6a129a2010-09-16 00:01:36 +0000860 // Finally we must make sure that openli is properly extended from Start to
861 // the new copy.
Jakob Stoklund Olesenfc60d772010-10-05 20:36:25 +0000862 openli_.addSimpleRange(Start, VNI->def, ParentVNI);
Jakob Stoklund Olesen9b24afe2010-10-07 17:56:35 +0000863 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000864}
865
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000866/// closeIntv - Indicate that we are done editing the currently open
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000867/// LiveInterval, and ranges can be trimmed.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000868void SplitEditor::closeIntv() {
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000869 assert(openli_.getLI() && "openIntv not called before closeIntv");
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +0000870
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +0000871 DEBUG(dbgs() << " closeIntv cleaning up\n");
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000872 DEBUG(dbgs() << " open " << *openli_.getLI() << '\n');
Jakob Stoklund Olesendd9f3fd2010-09-13 23:29:11 +0000873 openli_.reset(0);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +0000874}
875
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000876/// rewrite - Rewrite all uses of reg to use the new registers.
877void SplitEditor::rewrite(unsigned reg) {
878 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(reg),
879 RE = mri_.reg_end(); RI != RE;) {
880 MachineOperand &MO = RI.getOperand();
Jakob Stoklund Olesen79cb53c2010-11-01 21:51:29 +0000881 unsigned OpNum = RI.getOperandNo();
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000882 MachineInstr *MI = MO.getParent();
883 ++RI;
884 if (MI->isDebugValue()) {
885 DEBUG(dbgs() << "Zapping " << *MI);
886 // FIXME: We can do much better with debug values.
887 MO.setReg(0);
888 continue;
889 }
890 SlotIndex Idx = lis_.getInstructionIndex(MI);
891 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
892 LiveInterval *LI = 0;
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000893 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E;
894 ++I) {
895 LiveInterval *testli = *I;
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000896 if (testli->liveAt(Idx)) {
897 LI = testli;
898 break;
899 }
900 }
Jakob Stoklund Olesen9d999772010-10-21 18:47:08 +0000901 DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t'<< Idx);
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000902 assert(LI && "No register was live at use");
903 MO.setReg(LI->reg);
Jakob Stoklund Olesen79cb53c2010-11-01 21:51:29 +0000904 if (MO.isUse() && !MI->isRegTiedToDefOperand(OpNum))
905 MO.setIsKill(LI->killedAt(Idx.getDefIndex()));
Jakob Stoklund Olesen9d999772010-10-21 18:47:08 +0000906 DEBUG(dbgs() << '\t' << *MI);
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000907 }
908}
909
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000910void
911SplitEditor::addTruncSimpleRange(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000912 // Build vector of iterator pairs from the intervals.
913 typedef std::pair<LiveInterval::const_iterator,
914 LiveInterval::const_iterator> IIPair;
915 SmallVector<IIPair, 8> Iters;
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000916 for (LiveRangeEdit::iterator LI = edit_.begin(), LE = edit_.end(); LI != LE;
917 ++LI) {
Jakob Stoklund Olesen9d999772010-10-21 18:47:08 +0000918 if (*LI == dupli_.getLI())
919 continue;
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000920 LiveInterval::const_iterator I = (*LI)->find(Start);
921 LiveInterval::const_iterator E = (*LI)->end();
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000922 if (I != E)
923 Iters.push_back(std::make_pair(I, E));
924 }
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000925
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000926 SlotIndex sidx = Start;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000927 // Break [Start;End) into segments that don't overlap any intervals.
928 for (;;) {
929 SlotIndex next = sidx, eidx = End;
930 // Find overlapping intervals.
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000931 for (unsigned i = 0; i != Iters.size() && sidx < eidx; ++i) {
932 LiveInterval::const_iterator I = Iters[i].first;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000933 // Interval I is overlapping [sidx;eidx). Trim sidx.
934 if (I->start <= sidx) {
935 sidx = I->end;
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000936 // Move to the next run, remove iters when all are consumed.
937 I = ++Iters[i].first;
938 if (I == Iters[i].second) {
939 Iters.erase(Iters.begin() + i);
940 --i;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000941 continue;
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000942 }
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000943 }
944 // Trim eidx too if needed.
945 if (I->start >= eidx)
946 continue;
947 eidx = I->start;
Jakob Stoklund Olesen4b3041c2010-10-07 17:56:39 +0000948 next = I->end;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000949 }
950 // Now, [sidx;eidx) doesn't overlap anything in intervals_.
951 if (sidx < eidx)
952 dupli_.addSimpleRange(sidx, eidx, VNI);
953 // If the interval end was truncated, we can try again from next.
954 if (next <= sidx)
955 break;
956 sidx = next;
957 }
958}
959
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +0000960void SplitEditor::computeRemainder() {
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000961 // First we need to fill in the live ranges in dupli.
962 // If values were redefined, we need a full recoloring with SSA update.
963 // If values were truncated, we only need to truncate the ranges.
964 // If values were partially rematted, we should shrink to uses.
965 // If values were fully rematted, they should be omitted.
966 // FIXME: If a single value is redefined, just move the def and truncate.
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000967 LiveInterval &parent = edit_.getParent();
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000968
969 // Values that are fully contained in the split intervals.
970 SmallPtrSet<const VNInfo*, 8> deadValues;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000971 // Map all curli values that should have live defs in dupli.
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000972 for (LiveInterval::const_vni_iterator I = parent.vni_begin(),
973 E = parent.vni_end(); I != E; ++I) {
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000974 const VNInfo *VNI = *I;
Jakob Stoklund Olesen3ccfce02010-10-29 17:47:49 +0000975 // Don't transfer unused values to the new intervals.
976 if (VNI->isUnused())
977 continue;
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000978 // Original def is contained in the split intervals.
979 if (intervalsLiveAt(VNI->def)) {
980 // Did this value escape?
981 if (dupli_.isMapped(VNI))
982 truncatedValues.insert(VNI);
983 else
984 deadValues.insert(VNI);
985 continue;
986 }
987 // Add minimal live range at the definition.
988 VNInfo *DVNI = dupli_.defValue(VNI, VNI->def);
989 dupli_.getLI()->addRange(LiveRange(VNI->def, VNI->def.getNextSlot(), DVNI));
990 }
991
992 // Add all ranges to dupli.
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +0000993 for (LiveInterval::const_iterator I = parent.begin(), E = parent.end();
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +0000994 I != E; ++I) {
995 const LiveRange &LR = *I;
996 if (truncatedValues.count(LR.valno)) {
997 // recolor after removing intervals_.
998 addTruncSimpleRange(LR.start, LR.end, LR.valno);
999 } else if (!deadValues.count(LR.valno)) {
1000 // recolor without truncation.
1001 dupli_.addSimpleRange(LR.start, LR.end, LR.valno);
1002 }
1003 }
Jakob Stoklund Olesenc95c1462010-10-27 00:39:07 +00001004
1005 // Extend dupli_ to be live out of any critical loop predecessors.
1006 // This means we have multiple registers live out of those blocks.
1007 // The alternative would be to split the critical edges.
1008 if (criticalPreds_.empty())
1009 return;
1010 for (SplitAnalysis::BlockPtrSet::iterator I = criticalPreds_.begin(),
1011 E = criticalPreds_.end(); I != E; ++I)
1012 dupli_.extendTo(*I, lis_.getMBBEndIdx(*I).getPrevSlot());
1013 criticalPreds_.clear();
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +00001014}
1015
1016void SplitEditor::finish() {
1017 assert(!openli_.getLI() && "Previous LI not closed before rewrite");
1018 assert(dupli_.getLI() && "No dupli for rewrite. Noop spilt?");
1019
1020 // Complete dupli liveness.
1021 computeRemainder();
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +00001022
Jakob Stoklund Olesen0253df92010-10-07 23:34:34 +00001023 // Get rid of unused values and set phi-kill flags.
Jakob Stoklund Olesenf1354ae2010-10-26 22:36:05 +00001024 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I)
1025 (*I)->RenumberValues(lis_);
Jakob Stoklund Olesen5fa42a42010-09-21 22:32:21 +00001026
Jakob Stoklund Olesen0253df92010-10-07 23:34:34 +00001027 // Rewrite instructions.
Jakob Stoklund Olesen9d5d48b2010-10-15 00:34:01 +00001028 rewrite(edit_.getReg());
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +00001029
Jakob Stoklund Olesen3a0e0712010-10-26 22:36:09 +00001030 // Now check if any registers were separated into multiple components.
1031 ConnectedVNInfoEqClasses ConEQ(lis_);
1032 for (unsigned i = 0, e = edit_.size(); i != e; ++i) {
1033 // Don't use iterators, they are invalidated by create() below.
1034 LiveInterval *li = edit_.get(i);
1035 unsigned NumComp = ConEQ.Classify(li);
1036 if (NumComp <= 1)
1037 continue;
1038 DEBUG(dbgs() << " " << NumComp << " components: " << *li << '\n');
1039 SmallVector<LiveInterval*, 8> dups;
1040 dups.push_back(li);
1041 for (unsigned i = 1; i != NumComp; ++i)
1042 dups.push_back(&edit_.create(mri_, lis_, vrm_));
1043 ConEQ.Distribute(&dups[0]);
1044 // Rewrite uses to the new regs.
1045 rewrite(li->reg);
1046 }
1047
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +00001048 // Calculate spill weight and allocation hints for new intervals.
1049 VirtRegAuxInfo vrai(vrm_.getMachineFunction(), lis_, sa_.loops_);
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +00001050 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I){
1051 LiveInterval &li = **I;
Jakob Stoklund Olesen9db3ea42010-08-10 18:37:40 +00001052 vrai.CalculateRegClass(li.reg);
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +00001053 vrai.CalculateWeightAndHint(li);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +00001054 DEBUG(dbgs() << " new interval " << mri_.getRegClass(li.reg)->getName()
1055 << ":" << li << '\n');
Jakob Stoklund Olesen08e93b12010-08-10 17:07:22 +00001056 }
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001057}
1058
1059
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +00001060//===----------------------------------------------------------------------===//
1061// Loop Splitting
1062//===----------------------------------------------------------------------===//
1063
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +00001064void SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001065 SplitAnalysis::LoopBlocks Blocks;
1066 sa_.getLoopBlocks(Loop, Blocks);
1067
Jakob Stoklund Olesen452a9fd2010-10-07 18:47:07 +00001068 DEBUG({
Jakob Stoklund Olesen532de3d2010-10-22 20:28:21 +00001069 dbgs() << " splitAround"; sa_.print(Blocks, dbgs()); dbgs() << '\n';
Jakob Stoklund Olesen452a9fd2010-10-07 18:47:07 +00001070 });
1071
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001072 // Break critical edges as needed.
1073 SplitAnalysis::BlockPtrSet CriticalExits;
1074 sa_.getCriticalExits(Blocks, CriticalExits);
1075 assert(CriticalExits.empty() && "Cannot break critical exits yet");
1076
Jakob Stoklund Olesenc95c1462010-10-27 00:39:07 +00001077 // Get critical predecessors so computeRemainder can deal with them.
1078 sa_.getCriticalPreds(Blocks, criticalPreds_);
1079
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001080 // Create new live interval for the loop.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +00001081 openIntv();
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001082
Jakob Stoklund Olesendfe3b6d2010-12-18 01:06:19 +00001083 // Insert copies in the predecessors if live-in to the header.
1084 if (lis_.isLiveInToMBB(edit_.getParent(), Loop->getHeader())) {
1085 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
1086 E = Blocks.Preds.end(); I != E; ++I) {
1087 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
1088 enterIntvAtEnd(MBB);
1089 }
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001090 }
1091
1092 // Switch all loop blocks.
1093 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
1094 E = Blocks.Loop.end(); I != E; ++I)
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +00001095 useIntv(**I);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001096
1097 // Insert back copies in the exit blocks.
1098 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
1099 E = Blocks.Exits.end(); I != E; ++I) {
1100 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +00001101 leaveIntvAtTop(MBB);
Jakob Stoklund Olesenf0179002010-07-26 23:44:11 +00001102 }
1103
1104 // Done.
Jakob Stoklund Olesen7536f722010-08-04 22:08:39 +00001105 closeIntv();
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +00001106 finish();
Jakob Stoklund Olesen8ae02632010-07-20 15:41:07 +00001107}
1108
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001109
1110//===----------------------------------------------------------------------===//
1111// Single Block Splitting
1112//===----------------------------------------------------------------------===//
1113
Jakob Stoklund Olesen2bfb3242010-10-22 22:48:56 +00001114/// getMultiUseBlocks - if curli has more than one use in a basic block, it
1115/// may be an advantage to split curli for the duration of the block.
1116bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
1117 // If curli is local to one block, there is no point to splitting it.
1118 if (usingBlocks_.size() <= 1)
1119 return false;
1120 // Add blocks with multiple uses.
1121 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
1122 I != E; ++I)
1123 switch (I->second) {
1124 case 0:
1125 case 1:
1126 continue;
1127 case 2: {
1128 // When there are only two uses and curli is both live in and live out,
1129 // we don't really win anything by isolating the block since we would be
1130 // inserting two copies.
1131 // The remaing register would still have two uses in the block. (Unless it
1132 // separates into disconnected components).
1133 if (lis_.isLiveInToMBB(*curli_, I->first) &&
1134 lis_.isLiveOutOfMBB(*curli_, I->first))
1135 continue;
1136 } // Fall through.
1137 default:
1138 Blocks.insert(I->first);
1139 }
1140 return !Blocks.empty();
1141}
1142
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001143/// splitSingleBlocks - Split curli into a separate live interval inside each
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +00001144/// basic block in Blocks.
1145void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +00001146 DEBUG(dbgs() << " splitSingleBlocks for " << Blocks.size() << " blocks.\n");
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001147 // Determine the first and last instruction using curli in each block.
1148 typedef std::pair<SlotIndex,SlotIndex> IndexPair;
1149 typedef DenseMap<const MachineBasicBlock*,IndexPair> IndexPairMap;
1150 IndexPairMap MBBRange;
1151 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1152 E = sa_.usingInstrs_.end(); I != E; ++I) {
1153 const MachineBasicBlock *MBB = (*I)->getParent();
1154 if (!Blocks.count(MBB))
1155 continue;
1156 SlotIndex Idx = lis_.getInstructionIndex(*I);
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +00001157 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '\t' << Idx << '\t' << **I);
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001158 IndexPair &IP = MBBRange[MBB];
1159 if (!IP.first.isValid() || Idx < IP.first)
1160 IP.first = Idx;
1161 if (!IP.second.isValid() || Idx > IP.second)
1162 IP.second = Idx;
1163 }
1164
1165 // Create a new interval for each block.
1166 for (SplitAnalysis::BlockPtrSet::const_iterator I = Blocks.begin(),
1167 E = Blocks.end(); I != E; ++I) {
1168 IndexPair &IP = MBBRange[*I];
Jakob Stoklund Olesene1f543f2010-08-12 18:50:55 +00001169 DEBUG(dbgs() << " splitting for BB#" << (*I)->getNumber() << ": ["
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001170 << IP.first << ';' << IP.second << ")\n");
1171 assert(IP.first.isValid() && IP.second.isValid());
1172
1173 openIntv();
1174 enterIntvBefore(IP.first);
1175 useIntv(IP.first.getBaseIndex(), IP.second.getBoundaryIndex());
1176 leaveIntvAfter(IP.second);
1177 closeIntv();
1178 }
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +00001179 finish();
Jakob Stoklund Olesenf1b05f22010-08-12 17:07:14 +00001180}
1181
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001182
1183//===----------------------------------------------------------------------===//
1184// Sub Block Splitting
1185//===----------------------------------------------------------------------===//
1186
1187/// getBlockForInsideSplit - If curli is contained inside a single basic block,
1188/// and it wou pay to subdivide the interval inside that block, return it.
1189/// Otherwise return NULL. The returned block can be passed to
1190/// SplitEditor::splitInsideBlock.
1191const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
1192 // The interval must be exclusive to one block.
1193 if (usingBlocks_.size() != 1)
1194 return 0;
1195 // Don't to this for less than 4 instructions. We want to be sure that
1196 // splitting actually reduces the instruction count per interval.
1197 if (usingInstrs_.size() < 4)
1198 return 0;
1199 return usingBlocks_.begin()->first;
1200}
1201
Jakob Stoklund Olesen57d0f2d2010-10-05 22:19:33 +00001202/// splitInsideBlock - Split curli into multiple intervals inside MBB.
1203void SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001204 SmallVector<SlotIndex, 32> Uses;
1205 Uses.reserve(sa_.usingInstrs_.size());
1206 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1207 E = sa_.usingInstrs_.end(); I != E; ++I)
1208 if ((*I)->getParent() == MBB)
1209 Uses.push_back(lis_.getInstructionIndex(*I));
1210 DEBUG(dbgs() << " splitInsideBlock BB#" << MBB->getNumber() << " for "
1211 << Uses.size() << " instructions.\n");
1212 assert(Uses.size() >= 3 && "Need at least 3 instructions");
1213 array_pod_sort(Uses.begin(), Uses.end());
1214
1215 // Simple algorithm: Find the largest gap between uses as determined by slot
1216 // indices. Create new intervals for instructions before the gap and after the
1217 // gap.
1218 unsigned bestPos = 0;
1219 int bestGap = 0;
1220 DEBUG(dbgs() << " dist (" << Uses[0]);
1221 for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
1222 int g = Uses[i-1].distance(Uses[i]);
1223 DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
1224 if (g > bestGap)
1225 bestPos = i, bestGap = g;
1226 }
1227 DEBUG(dbgs() << "), best: -" << bestGap << "-\n");
1228
1229 // bestPos points to the first use after the best gap.
1230 assert(bestPos > 0 && "Invalid gap");
1231
1232 // FIXME: Don't create intervals for low densities.
1233
1234 // First interval before the gap. Don't create single-instr intervals.
1235 if (bestPos > 1) {
1236 openIntv();
1237 enterIntvBefore(Uses.front());
1238 useIntv(Uses.front().getBaseIndex(), Uses[bestPos-1].getBoundaryIndex());
1239 leaveIntvAfter(Uses[bestPos-1]);
1240 closeIntv();
1241 }
1242
1243 // Second interval after the gap.
1244 if (bestPos < Uses.size()-1) {
1245 openIntv();
1246 enterIntvBefore(Uses[bestPos]);
1247 useIntv(Uses[bestPos].getBaseIndex(), Uses.back().getBoundaryIndex());
1248 leaveIntvAfter(Uses.back());
1249 closeIntv();
1250 }
1251
Jakob Stoklund Olesen74669272010-10-08 23:42:21 +00001252 finish();
Jakob Stoklund Olesenfc412d82010-08-13 21:18:48 +00001253}