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/Statistic.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
33 STATISTIC(NumSunk, "Number of machine instructions sunk");
36 class MachineSinking : public MachineFunctionPass {
37 const TargetInstrInfo *TII;
38 const TargetRegisterInfo *TRI;
39 MachineRegisterInfo *RegInfo; // Machine register information
40 MachineDominatorTree *DT; // Machine dominator tree
43 BitVector AllocatableSet; // Which physregs are allocatable?
46 static char ID; // Pass identification
47 MachineSinking() : MachineFunctionPass(&ID) {}
49 virtual bool runOnMachineFunction(MachineFunction &MF);
51 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
53 MachineFunctionPass::getAnalysisUsage(AU);
54 AU.addRequired<AliasAnalysis>();
55 AU.addRequired<MachineDominatorTree>();
56 AU.addRequired<MachineLoopInfo>();
57 AU.addPreserved<MachineDominatorTree>();
58 AU.addPreserved<MachineLoopInfo>();
61 bool ProcessBlock(MachineBasicBlock &MBB);
62 bool SinkInstruction(MachineInstr *MI, bool &SawStore);
63 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB) const;
65 } // end anonymous namespace
67 char MachineSinking::ID = 0;
68 static RegisterPass<MachineSinking>
69 X("machine-sink", "Machine code sinking");
71 FunctionPass *llvm::createMachineSinkingPass() { return new MachineSinking(); }
73 /// AllUsesDominatedByBlock - Return true if all uses of the specified register
74 /// occur in blocks dominated by the specified block.
75 bool MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
76 MachineBasicBlock *MBB) const {
77 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
78 "Only makes sense for vregs");
79 // Ignoring debug uses is necessary so debug info doesn't affect the code.
80 // This may leave a referencing dbg_value in the original block, before
81 // the definition of the vreg. Dwarf generator handles this although the
82 // user might not get the right info at runtime.
83 for (MachineRegisterInfo::use_nodbg_iterator I =
84 RegInfo->use_nodbg_begin(Reg),
85 E = RegInfo->use_nodbg_end(); I != E; ++I) {
86 // Determine the block of the use.
87 MachineInstr *UseInst = &*I;
88 MachineBasicBlock *UseBlock = UseInst->getParent();
89 if (UseInst->isPHI()) {
90 // PHI nodes use the operand in the predecessor block, not the block with
92 UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
94 // Check that it dominates.
95 if (!DT->dominates(MBB, UseBlock))
101 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
102 DEBUG(dbgs() << "******** Machine Sinking ********\n");
104 const TargetMachine &TM = MF.getTarget();
105 TII = TM.getInstrInfo();
106 TRI = TM.getRegisterInfo();
107 RegInfo = &MF.getRegInfo();
108 DT = &getAnalysis<MachineDominatorTree>();
109 LI = &getAnalysis<MachineLoopInfo>();
110 AA = &getAnalysis<AliasAnalysis>();
111 AllocatableSet = TRI->getAllocatableSet(MF);
113 bool EverMadeChange = false;
116 bool MadeChange = false;
118 // Process all basic blocks.
119 for (MachineFunction::iterator I = MF.begin(), E = MF.end();
121 MadeChange |= ProcessBlock(*I);
123 // If this iteration over the code changed anything, keep iterating.
124 if (!MadeChange) break;
125 EverMadeChange = true;
127 return EverMadeChange;
130 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
131 // Can't sink anything out of a block that has less than two successors.
132 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
134 // Don't bother sinking code out of unreachable blocks. In addition to being
135 // unprofitable, it can also lead to infinite looping, because in an unreachable
136 // loop there may be nowhere to stop.
137 if (!DT->isReachableFromEntry(&MBB)) return false;
139 bool MadeChange = false;
141 // Walk the basic block bottom-up. Remember if we saw a store.
142 MachineBasicBlock::iterator I = MBB.end();
144 bool ProcessedBegin, SawStore = false;
146 MachineInstr *MI = I; // The instruction to sink.
148 // Predecrement I (if it's not begin) so that it isn't invalidated by
150 ProcessedBegin = I == MBB.begin();
154 if (MI->isDebugValue())
157 if (SinkInstruction(MI, SawStore))
158 ++NumSunk, MadeChange = true;
160 // If we just processed the first instruction in the block, we're done.
161 } while (!ProcessedBegin);
166 /// SinkInstruction - Determine whether it is safe to sink the specified machine
167 /// instruction out of its current block into a successor.
168 bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
169 // Check if it's safe to move the instruction.
170 if (!MI->isSafeToMove(TII, AA, SawStore))
173 // FIXME: This should include support for sinking instructions within the
174 // block they are currently in to shorten the live ranges. We often get
175 // instructions sunk into the top of a large block, but it would be better to
176 // also sink them down before their first use in the block. This xform has to
177 // be careful not to *increase* register pressure though, e.g. sinking
178 // "x = y + z" down if it kills y and z would increase the live ranges of y
179 // and z and only shrink the live range of x.
181 // Loop over all the operands of the specified instruction. If there is
182 // anything we can't handle, bail out.
183 MachineBasicBlock *ParentBlock = MI->getParent();
185 // SuccToSinkTo - This is the successor to sink this instruction to, once we
187 MachineBasicBlock *SuccToSinkTo = 0;
189 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
190 const MachineOperand &MO = MI->getOperand(i);
191 if (!MO.isReg()) continue; // Ignore non-register operands.
193 unsigned Reg = MO.getReg();
194 if (Reg == 0) continue;
196 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
198 // If the physreg has no defs anywhere, it's just an ambient register
199 // and we can freely move its uses. Alternatively, if it's allocatable,
200 // it could get allocated to something with a def during allocation.
201 if (!RegInfo->def_empty(Reg))
203 if (AllocatableSet.test(Reg))
205 // Check for a def among the register's aliases too.
206 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
207 unsigned AliasReg = *Alias;
208 if (!RegInfo->def_empty(AliasReg))
210 if (AllocatableSet.test(AliasReg))
213 } else if (!MO.isDead()) {
214 // A def that isn't dead. We can't move it.
218 // Virtual register uses are always safe to sink.
219 if (MO.isUse()) continue;
221 // If it's not safe to move defs of the register class, then abort.
222 if (!TII->isSafeToMoveRegClassDefs(RegInfo->getRegClass(Reg)))
225 // FIXME: This picks a successor to sink into based on having one
226 // successor that dominates all the uses. However, there are cases where
227 // sinking can happen but where the sink point isn't a successor. For
232 // the instruction could be sunk over the whole diamond for the
233 // if/then/else (or loop, etc), allowing it to be sunk into other blocks
236 // Virtual register defs can only be sunk if all their uses are in blocks
237 // dominated by one of the successors.
239 // If a previous operand picked a block to sink to, then this operand
240 // must be sinkable to the same block.
241 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo))
246 // Otherwise, we should look at all the successors and decide which one
247 // we should sink to.
248 for (MachineBasicBlock::succ_iterator SI = ParentBlock->succ_begin(),
249 E = ParentBlock->succ_end(); SI != E; ++SI) {
250 if (AllUsesDominatedByBlock(Reg, *SI)) {
256 // If we couldn't find a block to sink to, ignore this instruction.
257 if (SuccToSinkTo == 0)
262 // If there are no outputs, it must have side-effects.
263 if (SuccToSinkTo == 0)
266 // It's not safe to sink instructions to EH landing pad. Control flow into
267 // landing pad is implicitly defined.
268 if (SuccToSinkTo->isLandingPad())
271 // It is not possible to sink an instruction into its own block. This can
272 // happen with loops.
273 if (MI->getParent() == SuccToSinkTo)
276 DEBUG(dbgs() << "Sink instr " << *MI);
277 DEBUG(dbgs() << "to block " << *SuccToSinkTo);
279 // If the block has multiple predecessors, this would introduce computation on
280 // a path that it doesn't already exist. We could split the critical edge,
281 // but for now we just punt.
282 // FIXME: Split critical edges if not backedges.
283 if (SuccToSinkTo->pred_size() > 1) {
284 // We cannot sink a load across a critical edge - there may be stores in
287 if (!MI->isSafeToMove(TII, AA, store)) {
288 DEBUG(dbgs() << " *** PUNTING: Wont sink load along critical edge.\n");
292 // We don't want to sink across a critical edge if we don't dominate the
293 // successor. We could be introducing calculations to new code paths.
294 if (!DT->dominates(ParentBlock, SuccToSinkTo)) {
295 DEBUG(dbgs() << " *** PUNTING: Critical edge found\n");
299 // Don't sink instructions into a loop.
300 if (LI->isLoopHeader(SuccToSinkTo)) {
301 DEBUG(dbgs() << " *** PUNTING: Loop header found\n");
305 // Otherwise we are OK with sinking along a critical edge.
306 DEBUG(dbgs() << "Sinking along critical edge.\n");
309 // Determine where to insert into. Skip phi nodes.
310 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
311 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
314 // Move the instruction.
315 SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
316 ++MachineBasicBlock::iterator(MI));