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(false), cl::Hidden);
39 static cl::opt<unsigned>
40 SplitLimit("split-limit",
41 cl::init(~0u), cl::Hidden);
43 STATISTIC(NumSunk, "Number of machine instructions sunk");
44 STATISTIC(NumSplit, "Number of critical edges split");
45 STATISTIC(NumCoalesces, "Number of copies coalesced");
48 class MachineSinking : public MachineFunctionPass {
49 const TargetInstrInfo *TII;
50 const TargetRegisterInfo *TRI;
51 MachineRegisterInfo *MRI; // Machine register information
52 MachineDominatorTree *DT; // Machine dominator tree
55 BitVector AllocatableSet; // Which physregs are allocatable?
57 // Remember which edges have been considered for breaking.
58 SmallSet<std::pair<MachineBasicBlock*,MachineBasicBlock*>, 8>
62 static char ID; // Pass identification
63 MachineSinking() : MachineFunctionPass(ID) {}
65 virtual bool runOnMachineFunction(MachineFunction &MF);
67 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
69 MachineFunctionPass::getAnalysisUsage(AU);
70 AU.addRequired<AliasAnalysis>();
71 AU.addRequired<MachineDominatorTree>();
72 AU.addRequired<MachineLoopInfo>();
73 AU.addPreserved<MachineDominatorTree>();
74 AU.addPreserved<MachineLoopInfo>();
77 virtual void releaseMemory() {
78 CEBCandidates.clear();
82 bool ProcessBlock(MachineBasicBlock &MBB);
83 bool isWorthBreakingCriticalEdge(MachineInstr *MI,
84 MachineBasicBlock *From,
85 MachineBasicBlock *To);
86 MachineBasicBlock *SplitCriticalEdge(MachineInstr *MI,
87 MachineBasicBlock *From,
88 MachineBasicBlock *To,
90 bool SinkInstruction(MachineInstr *MI, bool &SawStore);
91 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
92 MachineBasicBlock *DefMBB,
93 bool &BreakPHIEdge, bool &LocalUse) const;
94 bool PerformTrivialForwardCoalescing(MachineInstr *MI,
95 MachineBasicBlock *MBB);
97 } // end anonymous namespace
99 char MachineSinking::ID = 0;
100 INITIALIZE_PASS(MachineSinking, "machine-sink",
101 "Machine code sinking", false, false);
103 FunctionPass *llvm::createMachineSinkingPass() { return new MachineSinking(); }
105 bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr *MI,
106 MachineBasicBlock *MBB) {
110 unsigned SrcReg = MI->getOperand(1).getReg();
111 unsigned DstReg = MI->getOperand(0).getReg();
112 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
113 !TargetRegisterInfo::isVirtualRegister(DstReg) ||
114 !MRI->hasOneNonDBGUse(SrcReg))
117 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
118 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
122 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
123 if (DefMI->isCopyLike())
125 DEBUG(dbgs() << "Coalescing: " << *DefMI);
126 DEBUG(dbgs() << "*** to: " << *MI);
127 MRI->replaceRegWith(DstReg, SrcReg);
128 MI->eraseFromParent();
133 /// AllUsesDominatedByBlock - Return true if all uses of the specified register
134 /// occur in blocks dominated by the specified block. If any use is in the
135 /// definition block, then return false since it is never legal to move def
138 MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
139 MachineBasicBlock *MBB,
140 MachineBasicBlock *DefMBB,
142 bool &LocalUse) const {
143 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
144 "Only makes sense for vregs");
146 if (MRI->use_nodbg_empty(Reg))
149 // Ignoring debug uses is necessary so debug info doesn't affect the code.
150 // This may leave a referencing dbg_value in the original block, before
151 // the definition of the vreg. Dwarf generator handles this although the
152 // user might not get the right info at runtime.
154 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
155 // into and they are all PHI nodes. In this case, machine-sink must break
156 // the critical edge first. e.g.
158 // BB#1: derived from LLVM BB %bb4.preheader
159 // Predecessors according to CFG: BB#0
161 // %reg16385<def> = DEC64_32r %reg16437, %EFLAGS<imp-def,dead>
163 // JE_4 <BB#37>, %EFLAGS<imp-use>
164 // Successors according to CFG: BB#37 BB#2
166 // BB#2: derived from LLVM BB %bb.nph
167 // Predecessors according to CFG: BB#0 BB#1
168 // %reg16386<def> = PHI %reg16434, <BB#0>, %reg16385, <BB#1>
170 for (MachineRegisterInfo::use_nodbg_iterator
171 I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
173 MachineInstr *UseInst = &*I;
174 MachineBasicBlock *UseBlock = UseInst->getParent();
175 if (!(UseBlock == MBB && UseInst->isPHI() &&
176 UseInst->getOperand(I.getOperandNo()+1).getMBB() == DefMBB)) {
177 BreakPHIEdge = false;
184 for (MachineRegisterInfo::use_nodbg_iterator
185 I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
187 // Determine the block of the use.
188 MachineInstr *UseInst = &*I;
189 MachineBasicBlock *UseBlock = UseInst->getParent();
190 if (UseInst->isPHI()) {
191 // PHI nodes use the operand in the predecessor block, not the block with
193 UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
194 } else if (UseBlock == DefMBB) {
199 // Check that it dominates.
200 if (!DT->dominates(MBB, UseBlock))
207 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
208 DEBUG(dbgs() << "******** Machine Sinking ********\n");
210 const TargetMachine &TM = MF.getTarget();
211 TII = TM.getInstrInfo();
212 TRI = TM.getRegisterInfo();
213 MRI = &MF.getRegInfo();
214 DT = &getAnalysis<MachineDominatorTree>();
215 LI = &getAnalysis<MachineLoopInfo>();
216 AA = &getAnalysis<AliasAnalysis>();
217 AllocatableSet = TRI->getAllocatableSet(MF);
219 bool EverMadeChange = false;
222 bool MadeChange = false;
224 // Process all basic blocks.
225 CEBCandidates.clear();
226 for (MachineFunction::iterator I = MF.begin(), E = MF.end();
228 MadeChange |= ProcessBlock(*I);
230 // If this iteration over the code changed anything, keep iterating.
231 if (!MadeChange) break;
232 EverMadeChange = true;
234 return EverMadeChange;
237 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
238 // Can't sink anything out of a block that has less than two successors.
239 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
241 // Don't bother sinking code out of unreachable blocks. In addition to being
242 // unprofitable, it can also lead to infinite looping, because in an
243 // unreachable loop there may be nowhere to stop.
244 if (!DT->isReachableFromEntry(&MBB)) return false;
246 bool MadeChange = false;
248 // Walk the basic block bottom-up. Remember if we saw a store.
249 MachineBasicBlock::iterator I = MBB.end();
251 bool ProcessedBegin, SawStore = false;
253 MachineInstr *MI = I; // The instruction to sink.
255 // Predecrement I (if it's not begin) so that it isn't invalidated by
257 ProcessedBegin = I == MBB.begin();
261 if (MI->isDebugValue())
264 if (PerformTrivialForwardCoalescing(MI, &MBB))
267 if (SinkInstruction(MI, SawStore))
268 ++NumSunk, MadeChange = true;
270 // If we just processed the first instruction in the block, we're done.
271 } while (!ProcessedBegin);
276 bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr *MI,
277 MachineBasicBlock *From,
278 MachineBasicBlock *To) {
279 // FIXME: Need much better heuristics.
281 // If the pass has already considered breaking this edge (during this pass
282 // through the function), then let's go ahead and break it. This means
283 // sinking multiple "cheap" instructions into the same block.
284 if (!CEBCandidates.insert(std::make_pair(From, To)))
287 if (!(MI->isCopyLike() || MI->getDesc().isAsCheapAsAMove()))
290 // MI is cheap, we probably don't want to break the critical edge for it.
291 // However, if this would allow some definitions of its source operands
292 // to be sunk then it's probably worth it.
293 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
294 const MachineOperand &MO = MI->getOperand(i);
295 if (!MO.isReg()) continue;
296 unsigned Reg = MO.getReg();
297 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg))
299 if (MRI->hasOneNonDBGUse(Reg))
306 MachineBasicBlock *MachineSinking::SplitCriticalEdge(MachineInstr *MI,
307 MachineBasicBlock *FromBB,
308 MachineBasicBlock *ToBB,
310 if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
313 // Avoid breaking back edge. From == To means backedge for single BB loop.
314 if (!SplitEdges || NumSplit == SplitLimit || FromBB == ToBB)
317 // Check for backedges of more "complex" loops.
318 if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
319 LI->isLoopHeader(ToBB))
322 // It's not always legal to break critical edges and sink the computation
330 // ... no uses of v1024
336 // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted:
345 // ... no uses of v1024
351 // This is incorrect since v1024 is not computed along the BB#1->BB#2->BB#3
352 // flow. We need to ensure the new basic block where the computation is
353 // sunk to dominates all the uses.
354 // It's only legal to break critical edge and sink the computation to the
355 // new block if all the predecessors of "To", except for "From", are
356 // not dominated by "From". Given SSA property, this means these
357 // predecessors are dominated by "To".
359 // There is no need to do this check if all the uses are PHI nodes. PHI
360 // sources are only defined on the specific predecessor edges.
362 for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
363 E = ToBB->pred_end(); PI != E; ++PI) {
366 if (!DT->dominates(ToBB, *PI))
371 return FromBB->SplitCriticalEdge(ToBB, this);
374 /// SinkInstruction - Determine whether it is safe to sink the specified machine
375 /// instruction out of its current block into a successor.
376 bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
377 // Check if it's safe to move the instruction.
378 if (!MI->isSafeToMove(TII, AA, SawStore))
381 // FIXME: This should include support for sinking instructions within the
382 // block they are currently in to shorten the live ranges. We often get
383 // instructions sunk into the top of a large block, but it would be better to
384 // also sink them down before their first use in the block. This xform has to
385 // be careful not to *increase* register pressure though, e.g. sinking
386 // "x = y + z" down if it kills y and z would increase the live ranges of y
387 // and z and only shrink the live range of x.
389 // Loop over all the operands of the specified instruction. If there is
390 // anything we can't handle, bail out.
391 MachineBasicBlock *ParentBlock = MI->getParent();
393 // SuccToSinkTo - This is the successor to sink this instruction to, once we
395 MachineBasicBlock *SuccToSinkTo = 0;
397 bool BreakPHIEdge = false;
398 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
399 const MachineOperand &MO = MI->getOperand(i);
400 if (!MO.isReg()) continue; // Ignore non-register operands.
402 unsigned Reg = MO.getReg();
403 if (Reg == 0) continue;
405 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
407 // If the physreg has no defs anywhere, it's just an ambient register
408 // and we can freely move its uses. Alternatively, if it's allocatable,
409 // it could get allocated to something with a def during allocation.
410 if (!MRI->def_empty(Reg))
413 if (AllocatableSet.test(Reg))
416 // Check for a def among the register's aliases too.
417 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
418 unsigned AliasReg = *Alias;
419 if (!MRI->def_empty(AliasReg))
422 if (AllocatableSet.test(AliasReg))
425 } else if (!MO.isDead()) {
426 // A def that isn't dead. We can't move it.
430 // Virtual register uses are always safe to sink.
431 if (MO.isUse()) continue;
433 // If it's not safe to move defs of the register class, then abort.
434 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
437 // FIXME: This picks a successor to sink into based on having one
438 // successor that dominates all the uses. However, there are cases where
439 // sinking can happen but where the sink point isn't a successor. For
446 // the instruction could be sunk over the whole diamond for the
447 // if/then/else (or loop, etc), allowing it to be sunk into other blocks
450 // Virtual register defs can only be sunk if all their uses are in blocks
451 // dominated by one of the successors.
453 // If a previous operand picked a block to sink to, then this operand
454 // must be sinkable to the same block.
455 bool LocalUse = false;
456 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, ParentBlock,
457 BreakPHIEdge, LocalUse))
463 // Otherwise, we should look at all the successors and decide which one
464 // we should sink to.
465 for (MachineBasicBlock::succ_iterator SI = ParentBlock->succ_begin(),
466 E = ParentBlock->succ_end(); SI != E; ++SI) {
467 bool LocalUse = false;
468 if (AllUsesDominatedByBlock(Reg, *SI, ParentBlock,
469 BreakPHIEdge, LocalUse)) {
474 // Def is used locally, it's never safe to move this def.
478 // If we couldn't find a block to sink to, ignore this instruction.
479 if (SuccToSinkTo == 0)
484 // If there are no outputs, it must have side-effects.
485 if (SuccToSinkTo == 0)
488 // It's not safe to sink instructions to EH landing pad. Control flow into
489 // landing pad is implicitly defined.
490 if (SuccToSinkTo->isLandingPad())
493 // It is not possible to sink an instruction into its own block. This can
494 // happen with loops.
495 if (MI->getParent() == SuccToSinkTo)
498 // If the instruction to move defines a dead physical register which is live
499 // when leaving the basic block, don't move it because it could turn into a
500 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
501 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
502 const MachineOperand &MO = MI->getOperand(I);
503 if (!MO.isReg()) continue;
504 unsigned Reg = MO.getReg();
505 if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
506 if (SuccToSinkTo->isLiveIn(Reg))
510 DEBUG(dbgs() << "Sink instr " << *MI << "\tinto block " << *SuccToSinkTo);
512 // If the block has multiple predecessors, this would introduce computation on
513 // a path that it doesn't already exist. We could split the critical edge,
514 // but for now we just punt.
515 if (SuccToSinkTo->pred_size() > 1) {
516 // We cannot sink a load across a critical edge - there may be stores in
518 bool TryBreak = false;
520 if (!MI->isSafeToMove(TII, AA, store)) {
521 DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
525 // We don't want to sink across a critical edge if we don't dominate the
526 // successor. We could be introducing calculations to new code paths.
527 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
528 DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
532 // Don't sink instructions into a loop.
533 if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
534 DEBUG(dbgs() << " *** NOTE: Loop header found\n");
538 // Otherwise we are OK with sinking along a critical edge.
540 DEBUG(dbgs() << "Sinking along critical edge.\n");
542 MachineBasicBlock *NewSucc =
543 SplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
545 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
546 "break critical edge\n");
549 DEBUG(dbgs() << " *** Splitting critical edge:"
550 " BB#" << ParentBlock->getNumber()
551 << " -- BB#" << NewSucc->getNumber()
552 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
553 SuccToSinkTo = NewSucc;
555 BreakPHIEdge = false;
561 // BreakPHIEdge is true if all the uses are in the successor MBB being
562 // sunken into and they are all PHI nodes. In this case, machine-sink must
563 // break the critical edge first.
564 if (NumSplit == SplitLimit)
566 MachineBasicBlock *NewSucc = SplitCriticalEdge(MI, ParentBlock,
567 SuccToSinkTo, BreakPHIEdge);
569 DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
570 "break critical edge\n");
574 DEBUG(dbgs() << " *** Splitting critical edge:"
575 " BB#" << ParentBlock->getNumber()
576 << " -- BB#" << NewSucc->getNumber()
577 << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
578 SuccToSinkTo = NewSucc;
582 // Determine where to insert into. Skip phi nodes.
583 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
584 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
587 // Move the instruction.
588 SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
589 ++MachineBasicBlock::iterator(MI));
591 // Conservatively, clear any kill flags, since it's possible that they are no