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/Analysis/AliasAnalysis.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
33 STATISTIC(NumSunk, "Number of machine instructions sunk");
36 class VISIBILITY_HIDDEN MachineSinking : public MachineFunctionPass {
37 const TargetMachine *TM;
38 const TargetInstrInfo *TII;
39 const TargetRegisterInfo *TRI;
40 MachineFunction *CurMF; // Current MachineFunction
41 MachineRegisterInfo *RegInfo; // Machine register information
42 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.addPreserved<MachineDominatorTree>();
60 bool ProcessBlock(MachineBasicBlock &MBB);
61 bool SinkInstruction(MachineInstr *MI, bool &SawStore);
62 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB) const;
64 } // end anonymous namespace
66 char MachineSinking::ID = 0;
67 static RegisterPass<MachineSinking>
68 X("machine-sink", "Machine code sinking");
70 FunctionPass *llvm::createMachineSinkingPass() { return new MachineSinking(); }
72 /// AllUsesDominatedByBlock - Return true if all uses of the specified register
73 /// occur in blocks dominated by the specified block.
74 bool MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
75 MachineBasicBlock *MBB) const {
76 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
77 "Only makes sense for vregs");
78 for (MachineRegisterInfo::use_iterator I = RegInfo->use_begin(Reg),
79 E = RegInfo->use_end(); I != E; ++I) {
80 // Determine the block of the use.
81 MachineInstr *UseInst = &*I;
82 MachineBasicBlock *UseBlock = UseInst->getParent();
83 if (UseInst->getOpcode() == TargetInstrInfo::PHI) {
84 // PHI nodes use the operand in the predecessor block, not the block with
86 UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
88 // Check that it dominates.
89 if (!DT->dominates(MBB, UseBlock))
97 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
98 DEBUG(errs() << "******** Machine Sinking ********\n");
101 TM = &CurMF->getTarget();
102 TII = TM->getInstrInfo();
103 TRI = TM->getRegisterInfo();
104 RegInfo = &CurMF->getRegInfo();
105 DT = &getAnalysis<MachineDominatorTree>();
106 AA = &getAnalysis<AliasAnalysis>();
107 AllocatableSet = TRI->getAllocatableSet(*CurMF);
109 bool EverMadeChange = false;
112 bool MadeChange = false;
114 // Process all basic blocks.
115 for (MachineFunction::iterator I = CurMF->begin(), E = CurMF->end();
117 MadeChange |= ProcessBlock(*I);
119 // If this iteration over the code changed anything, keep iterating.
120 if (!MadeChange) break;
121 EverMadeChange = true;
123 return EverMadeChange;
126 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
127 // Can't sink anything out of a block that has less than two successors.
128 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
130 bool MadeChange = false;
132 // Walk the basic block bottom-up. Remember if we saw a store.
133 MachineBasicBlock::iterator I = MBB.end();
135 bool ProcessedBegin, SawStore = false;
137 MachineInstr *MI = I; // The instruction to sink.
139 // Predecrement I (if it's not begin) so that it isn't invalidated by
141 ProcessedBegin = I == MBB.begin();
145 if (SinkInstruction(MI, SawStore))
146 ++NumSunk, MadeChange = true;
148 // If we just processed the first instruction in the block, we're done.
149 } while (!ProcessedBegin);
154 /// SinkInstruction - Determine whether it is safe to sink the specified machine
155 /// instruction out of its current block into a successor.
156 bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
157 // Check if it's safe to move the instruction.
158 if (!MI->isSafeToMove(TII, SawStore, AA))
161 // FIXME: This should include support for sinking instructions within the
162 // block they are currently in to shorten the live ranges. We often get
163 // instructions sunk into the top of a large block, but it would be better to
164 // also sink them down before their first use in the block. This xform has to
165 // be careful not to *increase* register pressure though, e.g. sinking
166 // "x = y + z" down if it kills y and z would increase the live ranges of y
167 // and z and only shrink the live range of x.
169 // Loop over all the operands of the specified instruction. If there is
170 // anything we can't handle, bail out.
171 MachineBasicBlock *ParentBlock = MI->getParent();
173 // SuccToSinkTo - This is the successor to sink this instruction to, once we
175 MachineBasicBlock *SuccToSinkTo = 0;
177 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
178 const MachineOperand &MO = MI->getOperand(i);
179 if (!MO.isReg()) continue; // Ignore non-register operands.
181 unsigned Reg = MO.getReg();
182 if (Reg == 0) continue;
184 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
186 // If the physreg has no defs anywhere, it's just an ambient register
187 // and we can freely move its uses. Alternatively, if it's allocatable,
188 // it could get allocated to something with a def during allocation.
189 if (!RegInfo->def_empty(Reg))
191 if (AllocatableSet.test(Reg))
193 // Check for a def among the register's aliases too.
194 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
195 unsigned AliasReg = *Alias;
196 if (!RegInfo->def_empty(AliasReg))
198 if (AllocatableSet.test(AliasReg))
201 } else if (!MO.isDead()) {
202 // A def that isn't dead. We can't move it.
206 // Virtual register uses are always safe to sink.
207 if (MO.isUse()) continue;
209 // If it's not safe to move defs of the register class, then abort.
210 if (!TII->isSafeToMoveRegClassDefs(RegInfo->getRegClass(Reg)))
213 // FIXME: This picks a successor to sink into based on having one
214 // successor that dominates all the uses. However, there are cases where
215 // sinking can happen but where the sink point isn't a successor. For
220 // the instruction could be sunk over the whole diamond for the
221 // if/then/else (or loop, etc), allowing it to be sunk into other blocks
224 // Virtual register defs can only be sunk if all their uses are in blocks
225 // dominated by one of the successors.
227 // If a previous operand picked a block to sink to, then this operand
228 // must be sinkable to the same block.
229 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo))
234 // Otherwise, we should look at all the successors and decide which one
235 // we should sink to.
236 for (MachineBasicBlock::succ_iterator SI = ParentBlock->succ_begin(),
237 E = ParentBlock->succ_end(); SI != E; ++SI) {
238 if (AllUsesDominatedByBlock(Reg, *SI)) {
244 // If we couldn't find a block to sink to, ignore this instruction.
245 if (SuccToSinkTo == 0)
250 // If there are no outputs, it must have side-effects.
251 if (SuccToSinkTo == 0)
254 // It's not safe to sink instructions to EH landing pad. Control flow into
255 // landing pad is implicitly defined.
256 if (SuccToSinkTo->isLandingPad())
259 // If is not possible to sink an instruction into its own block. This can
260 // happen with loops.
261 if (MI->getParent() == SuccToSinkTo)
264 DEBUG(errs() << "Sink instr " << *MI);
265 DEBUG(errs() << "to block " << *SuccToSinkTo);
267 // If the block has multiple predecessors, this would introduce computation on
268 // a path that it doesn't already exist. We could split the critical edge,
269 // but for now we just punt.
270 // FIXME: Split critical edges if not backedges.
271 if (SuccToSinkTo->pred_size() > 1) {
272 DEBUG(errs() << " *** PUNTING: Critical edge found\n");
276 // Determine where to insert into. Skip phi nodes.
277 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
278 while (InsertPos != SuccToSinkTo->end() &&
279 InsertPos->getOpcode() == TargetInstrInfo::PHI)
282 // Move the instruction.
283 SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
284 ++MachineBasicBlock::iterator(MI));