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/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
36 SplitEdges("machine-sink-split",
37 cl::desc("Split critical edges during machine sinking"),
38 cl::init(true), cl::Hidden);
40 STATISTIC(NumSunk, "Number of machine instructions sunk");
41 STATISTIC(NumSplit, "Number of critical edges split");
42 STATISTIC(NumCoalesces, "Number of copies coalesced");
45 class MachineSinking : public MachineFunctionPass {
46 const TargetInstrInfo *TII;
47 const TargetRegisterInfo *TRI;
48 MachineRegisterInfo *MRI; // Machine register information
49 MachineDominatorTree *DT; // Machine dominator tree
52 BitVector AllocatableSet; // Which physregs are allocatable?
54 // Remember which edges have been considered for breaking.
55 SmallSet<std::pair<MachineBasicBlock*,MachineBasicBlock*>, 8>
59 static char ID; // Pass identification
60 MachineSinking() : MachineFunctionPass(ID) {
61 initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
64 virtual bool runOnMachineFunction(MachineFunction &MF);
66 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
68 MachineFunctionPass::getAnalysisUsage(AU);
69 AU.addRequired<AliasAnalysis>();
70 AU.addRequired<MachineDominatorTree>();
71 AU.addRequired<MachineLoopInfo>();
72 AU.addPreserved<MachineDominatorTree>();
73 AU.addPreserved<MachineLoopInfo>();
76 virtual void releaseMemory() {
77 CEBCandidates.clear();
81 bool ProcessBlock(MachineBasicBlock &MBB);
82 bool isWorthBreakingCriticalEdge(MachineInstr *MI,
83 MachineBasicBlock *From,
84 MachineBasicBlock *To);
85 MachineBasicBlock *SplitCriticalEdge(MachineInstr *MI,
86 MachineBasicBlock *From,
87 MachineBasicBlock *To,
89 bool SinkInstruction(MachineInstr *MI, bool &SawStore);
90 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
91 MachineBasicBlock *DefMBB,
92 bool &BreakPHIEdge, bool &LocalUse) const;
93 MachineBasicBlock *FindSuccToSinkTo(MachineInstr *MI, bool &BreakPHIEdge);
95 bool PerformTrivialForwardCoalescing(MachineInstr *MI,
96 MachineBasicBlock *MBB);
98 } // end anonymous namespace
100 char MachineSinking::ID = 0;
101 INITIALIZE_PASS_BEGIN(MachineSinking, "machine-sink",
102 "Machine code sinking", false, false)
103 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
104 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
105 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
106 INITIALIZE_PASS_END(MachineSinking, "machine-sink",
107 "Machine code sinking", false, false)
109 FunctionPass *llvm::createMachineSinkingPass() { return new MachineSinking(); }
111 bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr *MI,
112 MachineBasicBlock *MBB) {
116 unsigned SrcReg = MI->getOperand(1).getReg();
117 unsigned DstReg = MI->getOperand(0).getReg();
118 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
119 !TargetRegisterInfo::isVirtualRegister(DstReg) ||
120 !MRI->hasOneNonDBGUse(SrcReg))
123 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
124 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
128 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
129 if (DefMI->isCopyLike())
131 DEBUG(dbgs() << "Coalescing: " << *DefMI);
132 DEBUG(dbgs() << "*** to: " << *MI);
133 MRI->replaceRegWith(DstReg, SrcReg);
134 MI->eraseFromParent();
139 /// AllUsesDominatedByBlock - Return true if all uses of the specified register
140 /// occur in blocks dominated by the specified block. If any use is in the
141 /// definition block, then return false since it is never legal to move def
144 MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
145 MachineBasicBlock *MBB,
146 MachineBasicBlock *DefMBB,
148 bool &LocalUse) const {
149 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
150 "Only makes sense for vregs");
152 if (MRI->use_nodbg_empty(Reg))
155 // Ignoring debug uses because debug info doesn't affect the code.
157 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
158 // into and they are all PHI nodes. In this case, machine-sink must break
159 // the critical edge first. e.g.
161 // BB#1: derived from LLVM BB %bb4.preheader
162 // Predecessors according to CFG: BB#0
164 // %reg16385<def> = DEC64_32r %reg16437, %EFLAGS<imp-def,dead>
166 // JE_4 <BB#37>, %EFLAGS<imp-use>
167 // Successors according to CFG: BB#37 BB#2
169 // BB#2: derived from LLVM BB %bb.nph
170 // Predecessors according to CFG: BB#0 BB#1
171 // %reg16386<def> = PHI %reg16434, <BB#0>, %reg16385, <BB#1>
173 for (MachineRegisterInfo::use_nodbg_iterator
174 I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
176 MachineInstr *UseInst = &*I;
177 MachineBasicBlock *UseBlock = UseInst->getParent();
178 if (!(UseBlock == MBB && UseInst->isPHI() &&
179 UseInst->getOperand(I.getOperandNo()+1).getMBB() == DefMBB)) {
180 BreakPHIEdge = false;
187 for (MachineRegisterInfo::use_nodbg_iterator
188 I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
190 // Determine the block of the use.
191 MachineInstr *UseInst = &*I;
192 MachineBasicBlock *UseBlock = UseInst->getParent();
193 if (UseInst->isPHI()) {
194 // PHI nodes use the operand in the predecessor block, not the block with
196 UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
197 } else if (UseBlock == DefMBB) {
202 // Check that it dominates.
203 if (!DT->dominates(MBB, UseBlock))
210 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
211 DEBUG(dbgs() << "******** Machine Sinking ********\n");
213 const TargetMachine &TM = MF.getTarget();
214 TII = TM.getInstrInfo();
215 TRI = TM.getRegisterInfo();
216 MRI = &MF.getRegInfo();
217 DT = &getAnalysis<MachineDominatorTree>();
218 LI = &getAnalysis<MachineLoopInfo>();
219 AA = &getAnalysis<AliasAnalysis>();
220 AllocatableSet = TRI->getAllocatableSet(MF);
222 bool EverMadeChange = false;
225 bool MadeChange = false;
227 // Process all basic blocks.
228 CEBCandidates.clear();
229 for (MachineFunction::iterator I = MF.begin(), E = MF.end();
231 MadeChange |= ProcessBlock(*I);
233 // If this iteration over the code changed anything, keep iterating.
234 if (!MadeChange) break;
235 EverMadeChange = true;
237 return EverMadeChange;
240 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
241 // Can't sink anything out of a block that has less than two successors.
242 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
244 // Don't bother sinking code out of unreachable blocks. In addition to being
245 // unprofitable, it can also lead to infinite looping, because in an
246 // unreachable loop there may be nowhere to stop.
247 if (!DT->isReachableFromEntry(&MBB)) return false;
249 bool MadeChange = false;
251 // Walk the basic block bottom-up. Remember if we saw a store.
252 MachineBasicBlock::iterator I = MBB.end();
254 bool ProcessedBegin, SawStore = false;
256 MachineInstr *MI = I; // The instruction to sink.
258 // Predecrement I (if it's not begin) so that it isn't invalidated by
260 ProcessedBegin = I == MBB.begin();
264 if (MI->isDebugValue())
267 bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
273 if (SinkInstruction(MI, SawStore))
274 ++NumSunk, MadeChange = true;
276 // If we just processed the first instruction in the block, we're done.
277 } while (!ProcessedBegin);
282 bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr *MI,
283 MachineBasicBlock *From,
284 MachineBasicBlock *To) {
285 // FIXME: Need much better heuristics.
287 // If the pass has already considered breaking this edge (during this pass
288 // through the function), then let's go ahead and break it. This means
289 // sinking multiple "cheap" instructions into the same block.
290 if (!CEBCandidates.insert(std::make_pair(From, To)))
293 if (!MI->isCopy() && !MI->isAsCheapAsAMove())
296 // MI is cheap, we probably don't want to break the critical edge for it.
297 // However, if this would allow some definitions of its source operands
298 // to be sunk then it's probably worth it.
299 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
300 const MachineOperand &MO = MI->getOperand(i);
301 if (!MO.isReg()) continue;
302 unsigned Reg = MO.getReg();
303 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg))
305 if (MRI->hasOneNonDBGUse(Reg))
312 MachineBasicBlock *MachineSinking::SplitCriticalEdge(MachineInstr *MI,
313 MachineBasicBlock *FromBB,
314 MachineBasicBlock *ToBB,
316 if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
319 // Avoid breaking back edge. From == To means backedge for single BB loop.
320 if (!SplitEdges || FromBB == ToBB)
323 // Check for backedges of more "complex" loops.
324 if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
325 LI->isLoopHeader(ToBB))
328 // It's not always legal to break critical edges and sink the computation
336 // ... no uses of v1024
342 // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted:
351 // ... no uses of v1024
357 // This is incorrect since v1024 is not computed along the BB#1->BB#2->BB#3
358 // flow. We need to ensure the new basic block where the computation is
359 // sunk to dominates all the uses.
360 // It's only legal to break critical edge and sink the computation to the
361 // new block if all the predecessors of "To", except for "From", are
362 // not dominated by "From". Given SSA property, this means these
363 // predecessors are dominated by "To".
365 // There is no need to do this check if all the uses are PHI nodes. PHI
366 // sources are only defined on the specific predecessor edges.
368 for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
369 E = ToBB->pred_end(); PI != E; ++PI) {
372 if (!DT->dominates(ToBB, *PI))
377 return FromBB->SplitCriticalEdge(ToBB, this);
380 static bool AvoidsSinking(MachineInstr *MI, MachineRegisterInfo *MRI) {
381 return MI->isInsertSubreg() || MI->isSubregToReg() || MI->isRegSequence();
384 /// collectDebgValues - Scan instructions following MI and collect any
385 /// matching DBG_VALUEs.
386 static void collectDebugValues(MachineInstr *MI,
387 SmallVector<MachineInstr *, 2> & DbgValues) {
389 if (!MI->getOperand(0).isReg())
392 MachineBasicBlock::iterator DI = MI; ++DI;
393 for (MachineBasicBlock::iterator DE = MI->getParent()->end();
395 if (!DI->isDebugValue())
397 if (DI->getOperand(0).isReg() &&
398 DI->getOperand(0).getReg() == MI->getOperand(0).getReg())
399 DbgValues.push_back(DI);
403 /// FindSuccToSinkTo - Find a successor to sink this instruction to.
404 MachineBasicBlock *MachineSinking::FindSuccToSinkTo(MachineInstr *MI,
405 bool &BreakPHIEdge) {
407 // Loop over all the operands of the specified instruction. If there is
408 // anything we can't handle, bail out.
409 MachineBasicBlock *ParentBlock = MI->getParent();
411 // SuccToSinkTo - This is the successor to sink this instruction to, once we
413 MachineBasicBlock *SuccToSinkTo = 0;
415 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
416 const MachineOperand &MO = MI->getOperand(i);
417 if (!MO.isReg()) continue; // Ignore non-register operands.
419 unsigned Reg = MO.getReg();
420 if (Reg == 0) continue;
422 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
424 // If the physreg has no defs anywhere, it's just an ambient register
425 // and we can freely move its uses. Alternatively, if it's allocatable,
426 // it could get allocated to something with a def during allocation.
427 if (!MRI->def_empty(Reg))
430 if (AllocatableSet.test(Reg))
433 // Check for a def among the register's aliases too.
434 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
435 unsigned AliasReg = *Alias;
436 if (!MRI->def_empty(AliasReg))
439 if (AllocatableSet.test(AliasReg))
442 } else if (!MO.isDead()) {
443 // A def that isn't dead. We can't move it.
447 // Virtual register uses are always safe to sink.
448 if (MO.isUse()) continue;
450 // If it's not safe to move defs of the register class, then abort.
451 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
454 // FIXME: This picks a successor to sink into based on having one
455 // successor that dominates all the uses. However, there are cases where
456 // sinking can happen but where the sink point isn't a successor. For
463 // the instruction could be sunk over the whole diamond for the
464 // if/then/else (or loop, etc), allowing it to be sunk into other blocks
467 // Virtual register defs can only be sunk if all their uses are in blocks
468 // dominated by one of the successors.
470 // If a previous operand picked a block to sink to, then this operand
471 // must be sinkable to the same block.
472 bool LocalUse = false;
473 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, ParentBlock,
474 BreakPHIEdge, LocalUse))
480 // Otherwise, we should look at all the successors and decide which one
481 // we should sink to.
482 for (MachineBasicBlock::succ_iterator SI = ParentBlock->succ_begin(),
483 E = ParentBlock->succ_end(); SI != E; ++SI) {
484 MachineBasicBlock *SuccBlock = *SI;
485 bool LocalUse = false;
486 if (AllUsesDominatedByBlock(Reg, SuccBlock, ParentBlock,
487 BreakPHIEdge, LocalUse)) {
488 SuccToSinkTo = SuccBlock;
492 // Def is used locally, it's never safe to move this def.
496 // If we couldn't find a block to sink to, ignore this instruction.
497 if (SuccToSinkTo == 0)
502 // It is not possible to sink an instruction into its own block. This can
503 // happen with loops.
504 if (ParentBlock == SuccToSinkTo)
507 // It's not safe to sink instructions to EH landing pad. Control flow into
508 // landing pad is implicitly defined.
509 if (SuccToSinkTo && SuccToSinkTo->isLandingPad())
515 /// SinkInstruction - Determine whether it is safe to sink the specified machine
516 /// instruction out of its current block into a successor.
517 bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
518 // Don't sink insert_subreg, subreg_to_reg, reg_sequence. These are meant to
519 // be close to the source to make it easier to coalesce.
520 if (AvoidsSinking(MI, MRI))
523 // Check if it's safe to move the instruction.
524 if (!MI->isSafeToMove(TII, AA, SawStore))
527 // FIXME: This should include support for sinking instructions within the
528 // block they are currently in to shorten the live ranges. We often get
529 // instructions sunk into the top of a large block, but it would be better to
530 // also sink them down before their first use in the block. This xform has to
531 // be careful not to *increase* register pressure though, e.g. sinking
532 // "x = y + z" down if it kills y and z would increase the live ranges of y
533 // and z and only shrink the live range of x.
535 bool BreakPHIEdge = false;
536 MachineBasicBlock *SuccToSinkTo = FindSuccToSinkTo(MI, BreakPHIEdge);
538 // If there are no outputs, it must have side-effects.
539 if (SuccToSinkTo == 0)
543 // If the instruction to move defines a dead physical register which is live
544 // when leaving the basic block, don't move it because it could turn into a
545 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
546 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
547 const MachineOperand &MO = MI->getOperand(I);
548 if (!MO.isReg()) continue;
549 unsigned Reg = MO.getReg();
550 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
551 if (SuccToSinkTo->isLiveIn(Reg))
555 DEBUG(dbgs() << "Sink instr " << *MI << "\tinto block " << *SuccToSinkTo);
557 MachineBasicBlock *ParentBlock = MI->getParent();
559 // If the block has multiple predecessors, this would introduce computation on
560 // a path that it doesn't already exist. We could split the critical edge,
561 // but for now we just punt.
562 if (SuccToSinkTo->pred_size() > 1) {
563 // We cannot sink a load across a critical edge - there may be stores in
565 bool TryBreak = false;
567 if (!MI->isSafeToMove(TII, AA, store)) {
568 DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
572 // We don't want to sink across a critical edge if we don't dominate the
573 // successor. We could be introducing calculations to new code paths.
574 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
575 DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
579 // Don't sink instructions into a loop.
580 if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
581 DEBUG(dbgs() << " *** NOTE: Loop header found\n");
585 // Otherwise we are OK with sinking along a critical edge.
587 DEBUG(dbgs() << "Sinking along critical edge.\n");
589 MachineBasicBlock *NewSucc =
590 SplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
592 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
593 "break critical edge\n");
596 DEBUG(dbgs() << " *** Splitting critical edge:"
597 " BB#" << ParentBlock->getNumber()
598 << " -- BB#" << NewSucc->getNumber()
599 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
600 SuccToSinkTo = NewSucc;
602 BreakPHIEdge = false;
608 // BreakPHIEdge is true if all the uses are in the successor MBB being
609 // sunken into and they are all PHI nodes. In this case, machine-sink must
610 // break the critical edge first.
611 MachineBasicBlock *NewSucc = SplitCriticalEdge(MI, ParentBlock,
612 SuccToSinkTo, BreakPHIEdge);
614 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
615 "break critical edge\n");
619 DEBUG(dbgs() << " *** Splitting critical edge:"
620 " BB#" << ParentBlock->getNumber()
621 << " -- BB#" << NewSucc->getNumber()
622 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
623 SuccToSinkTo = NewSucc;
627 // Determine where to insert into. Skip phi nodes.
628 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
629 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
632 // collect matching debug values.
633 SmallVector<MachineInstr *, 2> DbgValuesToSink;
634 collectDebugValues(MI, DbgValuesToSink);
636 // Move the instruction.
637 SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
638 ++MachineBasicBlock::iterator(MI));
640 // Move debug values.
641 for (SmallVector<MachineInstr *, 2>::iterator DBI = DbgValuesToSink.begin(),
642 DBE = DbgValuesToSink.end(); DBI != DBE; ++DBI) {
643 MachineInstr *DbgMI = *DBI;
644 SuccToSinkTo->splice(InsertPos, ParentBlock, DbgMI,
645 ++MachineBasicBlock::iterator(DbgMI));
648 // Conservatively, clear any kill flags, since it's possible that they are no