1 //===-- llvm/CodeGen/Spiller.cpp - Spiller -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #define DEBUG_TYPE "spiller"
13 #include "VirtRegMap.h"
14 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
15 #include "llvm/CodeGen/MachineFrameInfo.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineInstrBuilder.h"
18 #include "llvm/CodeGen/MachineRegisterInfo.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Target/TargetInstrInfo.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/raw_ostream.h"
30 enum SpillerName { trivial, standard, splitting, inline_ };
33 static cl::opt<SpillerName>
35 cl::desc("Spiller to use: (default: standard)"),
37 cl::values(clEnumVal(trivial, "trivial spiller"),
38 clEnumVal(standard, "default spiller"),
39 clEnumVal(splitting, "splitting spiller"),
40 clEnumValN(inline_, "inline", "inline spiller"),
44 // Spiller virtual destructor implementation.
45 Spiller::~Spiller() {}
49 /// Utility class for spillers.
50 class SpillerBase : public Spiller {
54 MachineFrameInfo *mfi;
55 MachineRegisterInfo *mri;
56 const TargetInstrInfo *tii;
57 const TargetRegisterInfo *tri;
60 /// Construct a spiller base.
61 SpillerBase(MachineFunction *mf, LiveIntervals *lis, VirtRegMap *vrm)
62 : mf(mf), lis(lis), vrm(vrm)
64 mfi = mf->getFrameInfo();
65 mri = &mf->getRegInfo();
66 tii = mf->getTarget().getInstrInfo();
67 tri = mf->getTarget().getRegisterInfo();
70 /// Add spill ranges for every use/def of the live interval, inserting loads
71 /// immediately before each use, and stores after each def. No folding or
72 /// remat is attempted.
73 void trivialSpillEverywhere(LiveInterval *li,
74 std::vector<LiveInterval*> &newIntervals) {
75 DEBUG(dbgs() << "Spilling everywhere " << *li << "\n");
77 assert(li->weight != HUGE_VALF &&
78 "Attempting to spill already spilled value.");
80 assert(!li->isStackSlot() &&
81 "Trying to spill a stack slot.");
83 DEBUG(dbgs() << "Trivial spill everywhere of reg" << li->reg << "\n");
85 const TargetRegisterClass *trc = mri->getRegClass(li->reg);
86 unsigned ss = vrm->assignVirt2StackSlot(li->reg);
88 // Iterate over reg uses/defs.
89 for (MachineRegisterInfo::reg_iterator
90 regItr = mri->reg_begin(li->reg); regItr != mri->reg_end();) {
92 // Grab the use/def instr.
93 MachineInstr *mi = &*regItr;
95 DEBUG(dbgs() << " Processing " << *mi);
97 // Step regItr to the next use/def instr.
100 } while (regItr != mri->reg_end() && (&*regItr == mi));
102 // Collect uses & defs for this instr.
103 SmallVector<unsigned, 2> indices;
106 for (unsigned i = 0; i != mi->getNumOperands(); ++i) {
107 MachineOperand &op = mi->getOperand(i);
108 if (!op.isReg() || op.getReg() != li->reg)
110 hasUse |= mi->getOperand(i).isUse();
111 hasDef |= mi->getOperand(i).isDef();
112 indices.push_back(i);
115 // Create a new vreg & interval for this instr.
116 unsigned newVReg = mri->createVirtualRegister(trc);
118 vrm->assignVirt2StackSlot(newVReg, ss);
119 LiveInterval *newLI = &lis->getOrCreateInterval(newVReg);
120 newLI->weight = HUGE_VALF;
122 // Update the reg operands & kill flags.
123 for (unsigned i = 0; i < indices.size(); ++i) {
124 unsigned mopIdx = indices[i];
125 MachineOperand &mop = mi->getOperand(mopIdx);
127 if (mop.isUse() && !mi->isRegTiedToDefOperand(mopIdx)) {
131 assert(hasUse || hasDef);
133 // Insert reload if necessary.
134 MachineBasicBlock::iterator miItr(mi);
136 tii->loadRegFromStackSlot(*mi->getParent(), miItr, newVReg, ss, trc,
138 MachineInstr *loadInstr(prior(miItr));
139 SlotIndex loadIndex =
140 lis->InsertMachineInstrInMaps(loadInstr).getDefIndex();
141 vrm->addSpillSlotUse(ss, loadInstr);
142 SlotIndex endIndex = loadIndex.getNextIndex();
144 newLI->getNextValue(loadIndex, 0, true, lis->getVNInfoAllocator());
145 newLI->addRange(LiveRange(loadIndex, endIndex, loadVNI));
148 // Insert store if necessary.
150 tii->storeRegToStackSlot(*mi->getParent(), llvm::next(miItr), newVReg,
152 MachineInstr *storeInstr(llvm::next(miItr));
153 SlotIndex storeIndex =
154 lis->InsertMachineInstrInMaps(storeInstr).getDefIndex();
155 vrm->addSpillSlotUse(ss, storeInstr);
156 SlotIndex beginIndex = storeIndex.getPrevIndex();
158 newLI->getNextValue(beginIndex, 0, true, lis->getVNInfoAllocator());
159 newLI->addRange(LiveRange(beginIndex, storeIndex, storeVNI));
162 newIntervals.push_back(newLI);
167 } // end anonymous namespace
171 /// Spills any live range using the spill-everywhere method with no attempt at
173 class TrivialSpiller : public SpillerBase {
176 TrivialSpiller(MachineFunction *mf, LiveIntervals *lis, VirtRegMap *vrm)
177 : SpillerBase(mf, lis, vrm) {}
179 void spill(LiveInterval *li,
180 std::vector<LiveInterval*> &newIntervals,
181 SmallVectorImpl<LiveInterval*> &,
183 // Ignore spillIs - we don't use it.
184 trivialSpillEverywhere(li, newIntervals);
188 } // end anonymous namespace
192 /// Falls back on LiveIntervals::addIntervalsForSpills.
193 class StandardSpiller : public Spiller {
196 const MachineLoopInfo *loopInfo;
199 StandardSpiller(LiveIntervals *lis, const MachineLoopInfo *loopInfo,
201 : lis(lis), loopInfo(loopInfo), vrm(vrm) {}
203 /// Falls back on LiveIntervals::addIntervalsForSpills.
204 void spill(LiveInterval *li,
205 std::vector<LiveInterval*> &newIntervals,
206 SmallVectorImpl<LiveInterval*> &spillIs,
208 std::vector<LiveInterval*> added =
209 lis->addIntervalsForSpills(*li, spillIs, loopInfo, *vrm);
210 newIntervals.insert(newIntervals.end(), added.begin(), added.end());
214 } // end anonymous namespace
218 /// When a call to spill is placed this spiller will first try to break the
219 /// interval up into its component values (one new interval per value).
220 /// If this fails, or if a call is placed to spill a previously split interval
221 /// then the spiller falls back on the standard spilling mechanism.
222 class SplittingSpiller : public StandardSpiller {
224 SplittingSpiller(MachineFunction *mf, LiveIntervals *lis,
225 const MachineLoopInfo *loopInfo, VirtRegMap *vrm)
226 : StandardSpiller(lis, loopInfo, vrm) {
228 mri = &mf->getRegInfo();
229 tii = mf->getTarget().getInstrInfo();
230 tri = mf->getTarget().getRegisterInfo();
233 void spill(LiveInterval *li,
234 std::vector<LiveInterval*> &newIntervals,
235 SmallVectorImpl<LiveInterval*> &spillIs,
236 SlotIndex *earliestStart) {
237 if (worthTryingToSplit(li))
238 tryVNISplit(li, earliestStart);
240 StandardSpiller::spill(li, newIntervals, spillIs, earliestStart);
245 MachineRegisterInfo *mri;
246 const TargetInstrInfo *tii;
247 const TargetRegisterInfo *tri;
248 DenseSet<LiveInterval*> alreadySplit;
250 bool worthTryingToSplit(LiveInterval *li) const {
251 return (!alreadySplit.count(li) && li->getNumValNums() > 1);
254 /// Try to break a LiveInterval into its component values.
255 std::vector<LiveInterval*> tryVNISplit(LiveInterval *li,
256 SlotIndex *earliestStart) {
258 DEBUG(dbgs() << "Trying VNI split of %reg" << *li << "\n");
260 std::vector<LiveInterval*> added;
261 SmallVector<VNInfo*, 4> vnis;
263 std::copy(li->vni_begin(), li->vni_end(), std::back_inserter(vnis));
265 for (SmallVectorImpl<VNInfo*>::iterator vniItr = vnis.begin(),
266 vniEnd = vnis.end(); vniItr != vniEnd; ++vniItr) {
267 VNInfo *vni = *vniItr;
273 DEBUG(dbgs() << " Extracted Val #" << vni->id << " as ");
274 LiveInterval *splitInterval = extractVNI(li, vni);
276 if (splitInterval != 0) {
277 DEBUG(dbgs() << *splitInterval << "\n");
278 added.push_back(splitInterval);
279 alreadySplit.insert(splitInterval);
280 if (earliestStart != 0) {
281 if (splitInterval->beginIndex() < *earliestStart)
282 *earliestStart = splitInterval->beginIndex();
285 DEBUG(dbgs() << "0\n");
289 DEBUG(dbgs() << "Original LI: " << *li << "\n");
291 // If there original interval still contains some live ranges
292 // add it to added and alreadySplit.
295 alreadySplit.insert(li);
296 if (earliestStart != 0) {
297 if (li->beginIndex() < *earliestStart)
298 *earliestStart = li->beginIndex();
305 /// Extract the given value number from the interval.
306 LiveInterval* extractVNI(LiveInterval *li, VNInfo *vni) const {
307 assert(vni->isDefAccurate() || vni->isPHIDef());
309 // Create a new vreg and live interval, copy VNI ranges over.
310 const TargetRegisterClass *trc = mri->getRegClass(li->reg);
311 unsigned newVReg = mri->createVirtualRegister(trc);
313 LiveInterval *newLI = &lis->getOrCreateInterval(newVReg);
314 VNInfo *newVNI = newLI->createValueCopy(vni, lis->getVNInfoAllocator());
316 // Start by copying all live ranges in the VN to the new interval.
317 for (LiveInterval::iterator rItr = li->begin(), rEnd = li->end();
318 rItr != rEnd; ++rItr) {
319 if (rItr->valno == vni) {
320 newLI->addRange(LiveRange(rItr->start, rItr->end, newVNI));
324 // Erase the old VNI & ranges.
325 li->removeValNo(vni);
327 // Collect all current uses of the register belonging to the given VNI.
328 // We'll use this to rename the register after we've dealt with the def.
329 std::set<MachineInstr*> uses;
330 for (MachineRegisterInfo::use_iterator
331 useItr = mri->use_begin(li->reg), useEnd = mri->use_end();
332 useItr != useEnd; ++useItr) {
333 uses.insert(&*useItr);
336 // Process the def instruction for this VNI.
337 if (newVNI->isPHIDef()) {
338 // Insert a copy at the start of the MBB. The range proceeding the
339 // copy will be attached to the original LiveInterval.
340 MachineBasicBlock *defMBB = lis->getMBBFromIndex(newVNI->def);
341 MachineInstr *copyMI = BuildMI(*defMBB, defMBB->begin(), DebugLoc(),
342 tii->get(TargetOpcode::COPY), newVReg)
343 .addReg(li->reg, RegState::Kill);
344 SlotIndex copyIdx = lis->InsertMachineInstrInMaps(copyMI);
345 VNInfo *phiDefVNI = li->getNextValue(lis->getMBBStartIdx(defMBB),
346 0, false, lis->getVNInfoAllocator());
347 phiDefVNI->setIsPHIDef(true);
348 li->addRange(LiveRange(phiDefVNI->def, copyIdx.getDefIndex(), phiDefVNI));
349 LiveRange *oldPHIDefRange =
350 newLI->getLiveRangeContaining(lis->getMBBStartIdx(defMBB));
352 // If the old phi def starts in the middle of the range chop it up.
353 if (oldPHIDefRange->start < lis->getMBBStartIdx(defMBB)) {
354 LiveRange oldPHIDefRange2(copyIdx.getDefIndex(), oldPHIDefRange->end,
355 oldPHIDefRange->valno);
356 oldPHIDefRange->end = lis->getMBBStartIdx(defMBB);
357 newLI->addRange(oldPHIDefRange2);
358 } else if (oldPHIDefRange->start == lis->getMBBStartIdx(defMBB)) {
359 // Otherwise if it's at the start of the range just trim it.
360 oldPHIDefRange->start = copyIdx.getDefIndex();
362 assert(false && "PHI def range doesn't cover PHI def?");
365 newVNI->def = copyIdx.getDefIndex();
366 newVNI->setCopy(copyMI);
367 newVNI->setIsPHIDef(false); // not a PHI def anymore.
368 newVNI->setIsDefAccurate(true);
370 // non-PHI def. Rename the def. If it's two-addr that means renaming the
371 // use and inserting a new copy too.
372 MachineInstr *defInst = lis->getInstructionFromIndex(newVNI->def);
373 // We'll rename this now, so we can remove it from uses.
375 unsigned defOpIdx = defInst->findRegisterDefOperandIdx(li->reg);
376 bool isTwoAddr = defInst->isRegTiedToUseOperand(defOpIdx),
377 twoAddrUseIsUndef = false;
379 for (unsigned i = 0; i < defInst->getNumOperands(); ++i) {
380 MachineOperand &mo = defInst->getOperand(i);
381 if (mo.isReg() && (mo.isDef() || isTwoAddr) && (mo.getReg()==li->reg)) {
383 if (isTwoAddr && mo.isUse() && mo.isUndef())
384 twoAddrUseIsUndef = true;
388 SlotIndex defIdx = lis->getInstructionIndex(defInst);
389 newVNI->def = defIdx.getDefIndex();
391 if (isTwoAddr && !twoAddrUseIsUndef) {
392 MachineBasicBlock *defMBB = defInst->getParent();
393 MachineInstr *copyMI = BuildMI(*defMBB, defInst, DebugLoc(),
394 tii->get(TargetOpcode::COPY), newVReg)
395 .addReg(li->reg, RegState::Kill);
396 SlotIndex copyIdx = lis->InsertMachineInstrInMaps(copyMI);
397 LiveRange *origUseRange =
398 li->getLiveRangeContaining(newVNI->def.getUseIndex());
399 origUseRange->end = copyIdx.getDefIndex();
400 VNInfo *copyVNI = newLI->getNextValue(copyIdx.getDefIndex(), copyMI,
401 true, lis->getVNInfoAllocator());
402 LiveRange copyRange(copyIdx.getDefIndex(),defIdx.getDefIndex(),copyVNI);
403 newLI->addRange(copyRange);
407 for (std::set<MachineInstr*>::iterator
408 usesItr = uses.begin(), usesEnd = uses.end();
409 usesItr != usesEnd; ++usesItr) {
410 MachineInstr *useInst = *usesItr;
411 SlotIndex useIdx = lis->getInstructionIndex(useInst);
412 LiveRange *useRange =
413 newLI->getLiveRangeContaining(useIdx.getUseIndex());
415 // If this use doesn't belong to the new interval skip it.
419 // This use doesn't belong to the VNI, skip it.
420 if (useRange->valno != newVNI)
423 // Check if this instr is two address.
424 unsigned useOpIdx = useInst->findRegisterUseOperandIdx(li->reg);
425 bool isTwoAddress = useInst->isRegTiedToDefOperand(useOpIdx);
427 // Rename uses (and defs for two-address instrs).
428 for (unsigned i = 0; i < useInst->getNumOperands(); ++i) {
429 MachineOperand &mo = useInst->getOperand(i);
430 if (mo.isReg() && (mo.isUse() || isTwoAddress) &&
431 (mo.getReg() == li->reg)) {
436 // If this is a two address instruction we've got some extra work to do.
438 // We modified the def operand, so we need to copy back to the original
440 MachineBasicBlock *useMBB = useInst->getParent();
441 MachineBasicBlock::iterator useItr(useInst);
442 MachineInstr *copyMI = BuildMI(*useMBB, llvm::next(useItr), DebugLoc(),
443 tii->get(TargetOpcode::COPY), newVReg)
444 .addReg(li->reg, RegState::Kill);
445 SlotIndex copyIdx = lis->InsertMachineInstrInMaps(copyMI);
447 // Change the old two-address defined range & vni to start at
448 // (and be defined by) the copy.
449 LiveRange *origDefRange =
450 li->getLiveRangeContaining(useIdx.getDefIndex());
451 origDefRange->start = copyIdx.getDefIndex();
452 origDefRange->valno->def = copyIdx.getDefIndex();
453 origDefRange->valno->setCopy(copyMI);
455 // Insert a new range & vni for the two-address-to-copy value. This
456 // will be attached to the new live interval.
458 newLI->getNextValue(useIdx.getDefIndex(), 0, true,
459 lis->getVNInfoAllocator());
460 LiveRange copyRange(useIdx.getDefIndex(),copyIdx.getDefIndex(),copyVNI);
461 newLI->addRange(copyRange);
465 // Iterate over any PHI kills - we'll need to insert new copies for them.
466 for (LiveInterval::iterator LRI = newLI->begin(), LRE = newLI->end();
468 if (LRI->valno != newVNI || LRI->end.isPHI())
470 SlotIndex killIdx = LRI->end;
471 MachineBasicBlock *killMBB = lis->getMBBFromIndex(killIdx);
472 MachineInstr *copyMI = BuildMI(*killMBB, killMBB->getFirstTerminator(),
473 DebugLoc(), tii->get(TargetOpcode::COPY),
475 .addReg(newVReg, RegState::Kill);
476 SlotIndex copyIdx = lis->InsertMachineInstrInMaps(copyMI);
478 // Save the current end. We may need it to add a new range if the
479 // current range runs of the end of the MBB.
480 SlotIndex newKillRangeEnd = LRI->end;
481 LRI->end = copyIdx.getDefIndex();
483 if (newKillRangeEnd != lis->getMBBEndIdx(killMBB)) {
484 assert(newKillRangeEnd > lis->getMBBEndIdx(killMBB) &&
485 "PHI kill range doesn't reach kill-block end. Not sane.");
486 newLI->addRange(LiveRange(lis->getMBBEndIdx(killMBB),
487 newKillRangeEnd, newVNI));
490 VNInfo *newKillVNI = li->getNextValue(copyIdx.getDefIndex(),
492 lis->getVNInfoAllocator());
493 newKillVNI->setHasPHIKill(true);
494 li->addRange(LiveRange(copyIdx.getDefIndex(),
495 lis->getMBBEndIdx(killMBB),
498 newVNI->setHasPHIKill(false);
505 } // end anonymous namespace
509 Spiller *createInlineSpiller(MachineFunction*,
511 const MachineLoopInfo*,
515 llvm::Spiller* llvm::createSpiller(MachineFunction *mf, LiveIntervals *lis,
516 const MachineLoopInfo *loopInfo,
518 switch (spillerOpt) {
519 default: assert(0 && "unknown spiller");
520 case trivial: return new TrivialSpiller(mf, lis, vrm);
521 case standard: return new StandardSpiller(lis, loopInfo, vrm);
522 case splitting: return new SplittingSpiller(mf, lis, loopInfo, vrm);
523 case inline_: return createInlineSpiller(mf, lis, loopInfo, vrm);