1 //===-- MachineSink.cpp - Sinking for machine instructions ----------------===//
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 // This pass moves instructions into successor blocks when possible, so that
11 // they aren't executed on paths where their results aren't needed.
13 // This pass is not intended to be a replacement or a complete alternative
14 // for an LLVM-IR-level sinking pass. It is only designed to sink simple
15 // constructs that are not exposed before lowering and instruction selection.
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "machine-sink"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/MachineDominators.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/Target/TargetRegisterInfo.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
34 STATISTIC(NumSunk, "Number of machine instructions sunk");
37 class MachineSinking : public MachineFunctionPass {
38 const TargetInstrInfo *TII;
39 const TargetRegisterInfo *TRI;
40 MachineRegisterInfo *RegInfo; // Machine register information
41 MachineDominatorTree *DT; // Machine dominator tree
44 BitVector AllocatableSet; // Which physregs are allocatable?
47 static char ID; // Pass identification
48 MachineSinking() : MachineFunctionPass(&ID) {}
50 virtual bool runOnMachineFunction(MachineFunction &MF);
52 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
54 MachineFunctionPass::getAnalysisUsage(AU);
55 AU.addRequired<AliasAnalysis>();
56 AU.addRequired<MachineDominatorTree>();
57 AU.addRequired<MachineLoopInfo>();
58 AU.addPreserved<MachineDominatorTree>();
59 AU.addPreserved<MachineLoopInfo>();
62 bool ProcessBlock(MachineBasicBlock &MBB);
63 bool SinkInstruction(MachineInstr *MI, bool &SawStore);
64 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB) const;
65 bool LiveOutOfBasicBlock(const MachineInstr *MI, unsigned Reg) const;
67 } // end anonymous namespace
69 char MachineSinking::ID = 0;
70 static RegisterPass<MachineSinking>
71 X("machine-sink", "Machine code sinking");
73 FunctionPass *llvm::createMachineSinkingPass() { return new MachineSinking(); }
75 /// AllUsesDominatedByBlock - Return true if all uses of the specified register
76 /// occur in blocks dominated by the specified block.
77 bool MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
78 MachineBasicBlock *MBB) const {
79 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
80 "Only makes sense for vregs");
81 // Ignoring debug uses is necessary so debug info doesn't affect the code.
82 // This may leave a referencing dbg_value in the original block, before
83 // the definition of the vreg. Dwarf generator handles this although the
84 // user might not get the right info at runtime.
85 for (MachineRegisterInfo::use_nodbg_iterator
86 I = RegInfo->use_nodbg_begin(Reg), E = RegInfo->use_nodbg_end();
88 // Determine the block of the use.
89 MachineInstr *UseInst = &*I;
90 MachineBasicBlock *UseBlock = UseInst->getParent();
92 if (UseInst->isPHI()) {
93 // PHI nodes use the operand in the predecessor block, not the block with
95 UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
98 // Check that it dominates.
99 if (!DT->dominates(MBB, UseBlock))
106 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
107 DEBUG(dbgs() << "******** Machine Sinking ********\n");
109 const TargetMachine &TM = MF.getTarget();
110 TII = TM.getInstrInfo();
111 TRI = TM.getRegisterInfo();
112 RegInfo = &MF.getRegInfo();
113 DT = &getAnalysis<MachineDominatorTree>();
114 LI = &getAnalysis<MachineLoopInfo>();
115 AA = &getAnalysis<AliasAnalysis>();
116 AllocatableSet = TRI->getAllocatableSet(MF);
118 bool EverMadeChange = false;
121 bool MadeChange = false;
123 // Process all basic blocks.
124 for (MachineFunction::iterator I = MF.begin(), E = MF.end();
126 MadeChange |= ProcessBlock(*I);
128 // If this iteration over the code changed anything, keep iterating.
129 if (!MadeChange) break;
130 EverMadeChange = true;
132 return EverMadeChange;
135 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
136 // Can't sink anything out of a block that has less than two successors.
137 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
139 // Don't bother sinking code out of unreachable blocks. In addition to being
140 // unprofitable, it can also lead to infinite looping, because in an
141 // unreachable loop there may be nowhere to stop.
142 if (!DT->isReachableFromEntry(&MBB)) return false;
144 bool MadeChange = false;
146 // Walk the basic block bottom-up. Remember if we saw a store.
147 MachineBasicBlock::iterator I = MBB.end();
149 bool ProcessedBegin, SawStore = false;
151 MachineInstr *MI = I; // The instruction to sink.
153 // Predecrement I (if it's not begin) so that it isn't invalidated by
155 ProcessedBegin = I == MBB.begin();
159 if (MI->isDebugValue())
162 if (SinkInstruction(MI, SawStore))
163 ++NumSunk, MadeChange = true;
165 // If we just processed the first instruction in the block, we're done.
166 } while (!ProcessedBegin);
171 /// LiveOutOfBasicBlock - Determine if the physical register, defined and dead
172 /// in MI, is live on exit from the basic block.
173 bool MachineSinking::LiveOutOfBasicBlock(const MachineInstr *MI,
174 unsigned Reg) const {
175 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
176 "Only want to determine if a physical register is live out of a BB!");
178 const MachineBasicBlock *MBB = MI->getParent();
179 SmallSet<unsigned, 8> KilledRegs;
180 MachineBasicBlock::const_iterator I = MBB->end();
181 MachineBasicBlock::const_iterator E = MBB->begin();
182 assert(I != E && "How can there be an empty block at this point?!");
184 // Loop through the instructions bottom-up. If we see a kill of the preg
185 // first, then it's not live out of the BB. If we see a use or def first, then
186 // we assume that it is live out of the BB.
188 const MachineInstr &CurMI = *--I;
190 for (unsigned i = 0, e = CurMI.getNumOperands(); i != e; ++i) {
191 const MachineOperand &MO = CurMI.getOperand(i);
192 if (!MO.isReg()) continue; // Ignore non-register operands.
194 unsigned MOReg = MO.getReg();
195 if (MOReg == 0) continue;
200 if (MO.isUse() || MO.isDef())
209 /// SinkInstruction - Determine whether it is safe to sink the specified machine
210 /// instruction out of its current block into a successor.
211 bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
212 // Check if it's safe to move the instruction.
213 if (!MI->isSafeToMove(TII, AA, SawStore))
216 // FIXME: This should include support for sinking instructions within the
217 // block they are currently in to shorten the live ranges. We often get
218 // instructions sunk into the top of a large block, but it would be better to
219 // also sink them down before their first use in the block. This xform has to
220 // be careful not to *increase* register pressure though, e.g. sinking
221 // "x = y + z" down if it kills y and z would increase the live ranges of y
222 // and z and only shrink the live range of x.
224 // Loop over all the operands of the specified instruction. If there is
225 // anything we can't handle, bail out.
226 MachineBasicBlock *ParentBlock = MI->getParent();
228 // SuccToSinkTo - This is the successor to sink this instruction to, once we
230 MachineBasicBlock *SuccToSinkTo = 0;
231 SmallVector<unsigned, 4> PhysRegs;
233 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
234 const MachineOperand &MO = MI->getOperand(i);
235 if (!MO.isReg()) continue; // Ignore non-register operands.
237 unsigned Reg = MO.getReg();
238 if (Reg == 0) continue;
240 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
242 // If the physreg has no defs anywhere, it's just an ambient register
243 // and we can freely move its uses. Alternatively, if it's allocatable,
244 // it could get allocated to something with a def during allocation.
245 if (!RegInfo->def_empty(Reg))
248 if (AllocatableSet.test(Reg))
251 // Check for a def among the register's aliases too.
252 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
253 unsigned AliasReg = *Alias;
254 if (!RegInfo->def_empty(AliasReg))
257 if (AllocatableSet.test(AliasReg))
262 // A def that isn't dead. We can't move it.
265 PhysRegs.push_back(Reg);
268 // Virtual register uses are always safe to sink.
269 if (MO.isUse()) continue;
271 // If it's not safe to move defs of the register class, then abort.
272 if (!TII->isSafeToMoveRegClassDefs(RegInfo->getRegClass(Reg)))
275 // FIXME: This picks a successor to sink into based on having one
276 // successor that dominates all the uses. However, there are cases where
277 // sinking can happen but where the sink point isn't a successor. For
284 // the instruction could be sunk over the whole diamond for the
285 // if/then/else (or loop, etc), allowing it to be sunk into other blocks
288 // Virtual register defs can only be sunk if all their uses are in blocks
289 // dominated by one of the successors.
291 // If a previous operand picked a block to sink to, then this operand
292 // must be sinkable to the same block.
293 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo))
299 // Otherwise, we should look at all the successors and decide which one
300 // we should sink to.
301 for (MachineBasicBlock::succ_iterator SI = ParentBlock->succ_begin(),
302 E = ParentBlock->succ_end(); SI != E; ++SI) {
303 if (AllUsesDominatedByBlock(Reg, *SI)) {
309 // If we couldn't find a block to sink to, ignore this instruction.
310 if (SuccToSinkTo == 0)
315 // If there are no outputs, it must have side-effects.
316 if (SuccToSinkTo == 0)
319 // It's not safe to sink instructions to EH landing pad. Control flow into
320 // landing pad is implicitly defined.
321 if (SuccToSinkTo->isLandingPad())
324 // It is not possible to sink an instruction into its own block. This can
325 // happen with loops.
326 if (MI->getParent() == SuccToSinkTo)
329 // If the instruction to move defines a dead physical register which is live
330 // when leaving the basic block, don't move it because it could turn into a
331 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
332 for (SmallVectorImpl<unsigned>::const_iterator
333 I = PhysRegs.begin(), E = PhysRegs.end(); I != E; ++I)
334 if (LiveOutOfBasicBlock(MI, *I))
337 DEBUG(dbgs() << "Sink instr " << *MI << "\tinto block " << *SuccToSinkTo);
339 // If the block has multiple predecessors, this would introduce computation on
340 // a path that it doesn't already exist. We could split the critical edge,
341 // but for now we just punt.
342 // FIXME: Split critical edges if not backedges.
343 if (SuccToSinkTo->pred_size() > 1) {
344 // We cannot sink a load across a critical edge - there may be stores in
347 if (!MI->isSafeToMove(TII, AA, store)) {
348 DEBUG(dbgs() << " *** PUNTING: Wont sink load along critical edge.\n");
352 // We don't want to sink across a critical edge if we don't dominate the
353 // successor. We could be introducing calculations to new code paths.
354 if (!DT->dominates(ParentBlock, SuccToSinkTo)) {
355 DEBUG(dbgs() << " *** PUNTING: Critical edge found\n");
359 // Don't sink instructions into a loop.
360 if (LI->isLoopHeader(SuccToSinkTo)) {
361 DEBUG(dbgs() << " *** PUNTING: Loop header found\n");
365 // Otherwise we are OK with sinking along a critical edge.
366 DEBUG(dbgs() << "Sinking along critical edge.\n");
369 // Determine where to insert into. Skip phi nodes.
370 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
371 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
374 // Move the instruction.
375 SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
376 ++MachineBasicBlock::iterator(MI));
378 // Conservatively, clear any kill flags, since it's possible that they are no