1//===-- MachineSink.cpp - Sinking for machine instructions ----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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.
12//
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.
16//
17//===----------------------------------------------------------------------===//
18
19#define DEBUG_TYPE "machine-sink"
20#include "llvm/CodeGen/Passes.h"
21#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/CodeGen/MachineDominators.h"
25#include "llvm/CodeGen/MachineLoopInfo.h"
26#include "llvm/CodeGen/MachineRegisterInfo.h"
27#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/raw_ostream.h"
30#include "llvm/Target/TargetInstrInfo.h"
31#include "llvm/Target/TargetMachine.h"
32#include "llvm/Target/TargetRegisterInfo.h"
33using namespace llvm;
34
35static cl::opt<bool>
36SplitEdges("machine-sink-split",
37           cl::desc("Split critical edges during machine sinking"),
38           cl::init(true), cl::Hidden);
39
40STATISTIC(NumSunk,      "Number of machine instructions sunk");
41STATISTIC(NumSplit,     "Number of critical edges split");
42STATISTIC(NumCoalesces, "Number of copies coalesced");
43
44namespace {
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
50    MachineLoopInfo *LI;
51    AliasAnalysis *AA;
52
53    // Remember which edges have been considered for breaking.
54    SmallSet<std::pair<MachineBasicBlock*,MachineBasicBlock*>, 8>
55    CEBCandidates;
56
57  public:
58    static char ID; // Pass identification
59    MachineSinking() : MachineFunctionPass(ID) {
60      initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
61    }
62
63    virtual bool runOnMachineFunction(MachineFunction &MF);
64
65    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
66      AU.setPreservesCFG();
67      MachineFunctionPass::getAnalysisUsage(AU);
68      AU.addRequired<AliasAnalysis>();
69      AU.addRequired<MachineDominatorTree>();
70      AU.addRequired<MachineLoopInfo>();
71      AU.addPreserved<MachineDominatorTree>();
72      AU.addPreserved<MachineLoopInfo>();
73    }
74
75    virtual void releaseMemory() {
76      CEBCandidates.clear();
77    }
78
79  private:
80    bool ProcessBlock(MachineBasicBlock &MBB);
81    bool isWorthBreakingCriticalEdge(MachineInstr *MI,
82                                     MachineBasicBlock *From,
83                                     MachineBasicBlock *To);
84    MachineBasicBlock *SplitCriticalEdge(MachineInstr *MI,
85                                         MachineBasicBlock *From,
86                                         MachineBasicBlock *To,
87                                         bool BreakPHIEdge);
88    bool SinkInstruction(MachineInstr *MI, bool &SawStore);
89    bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
90                                 MachineBasicBlock *DefMBB,
91                                 bool &BreakPHIEdge, bool &LocalUse) const;
92    MachineBasicBlock *FindSuccToSinkTo(MachineInstr *MI, MachineBasicBlock *MBB,
93               bool &BreakPHIEdge);
94    bool isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
95                              MachineBasicBlock *MBB,
96                              MachineBasicBlock *SuccToSinkTo);
97
98    bool PerformTrivialForwardCoalescing(MachineInstr *MI,
99                                         MachineBasicBlock *MBB);
100  };
101
102  // SuccessorSorter - Sort Successors according to their loop depth.
103  struct SuccessorSorter {
104    SuccessorSorter(MachineLoopInfo *LoopInfo) : LI(LoopInfo) {}
105    bool operator()(const MachineBasicBlock *LHS,
106                    const MachineBasicBlock *RHS) const {
107      return LI->getLoopDepth(LHS) < LI->getLoopDepth(RHS);
108    }
109    MachineLoopInfo *LI;
110  };
111} // end anonymous namespace
112
113char MachineSinking::ID = 0;
114char &llvm::MachineSinkingID = MachineSinking::ID;
115INITIALIZE_PASS_BEGIN(MachineSinking, "machine-sink",
116                "Machine code sinking", false, false)
117INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
118INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
119INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
120INITIALIZE_PASS_END(MachineSinking, "machine-sink",
121                "Machine code sinking", false, false)
122
123bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr *MI,
124                                                     MachineBasicBlock *MBB) {
125  if (!MI->isCopy())
126    return false;
127
128  unsigned SrcReg = MI->getOperand(1).getReg();
129  unsigned DstReg = MI->getOperand(0).getReg();
130  if (!TargetRegisterInfo::isVirtualRegister(SrcReg) ||
131      !TargetRegisterInfo::isVirtualRegister(DstReg) ||
132      !MRI->hasOneNonDBGUse(SrcReg))
133    return false;
134
135  const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
136  const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
137  if (SRC != DRC)
138    return false;
139
140  MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
141  if (DefMI->isCopyLike())
142    return false;
143  DEBUG(dbgs() << "Coalescing: " << *DefMI);
144  DEBUG(dbgs() << "*** to: " << *MI);
145  MRI->replaceRegWith(DstReg, SrcReg);
146  MI->eraseFromParent();
147  ++NumCoalesces;
148  return true;
149}
150
151/// AllUsesDominatedByBlock - Return true if all uses of the specified register
152/// occur in blocks dominated by the specified block. If any use is in the
153/// definition block, then return false since it is never legal to move def
154/// after uses.
155bool
156MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
157                                        MachineBasicBlock *MBB,
158                                        MachineBasicBlock *DefMBB,
159                                        bool &BreakPHIEdge,
160                                        bool &LocalUse) const {
161  assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
162         "Only makes sense for vregs");
163
164  // Ignore debug uses because debug info doesn't affect the code.
165  if (MRI->use_nodbg_empty(Reg))
166    return true;
167
168  // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
169  // into and they are all PHI nodes. In this case, machine-sink must break
170  // the critical edge first. e.g.
171  //
172  // BB#1: derived from LLVM BB %bb4.preheader
173  //   Predecessors according to CFG: BB#0
174  //     ...
175  //     %reg16385<def> = DEC64_32r %reg16437, %EFLAGS<imp-def,dead>
176  //     ...
177  //     JE_4 <BB#37>, %EFLAGS<imp-use>
178  //   Successors according to CFG: BB#37 BB#2
179  //
180  // BB#2: derived from LLVM BB %bb.nph
181  //   Predecessors according to CFG: BB#0 BB#1
182  //     %reg16386<def> = PHI %reg16434, <BB#0>, %reg16385, <BB#1>
183  BreakPHIEdge = true;
184  for (MachineRegisterInfo::use_nodbg_iterator
185         I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
186       I != E; ++I) {
187    MachineInstr *UseInst = &*I;
188    MachineBasicBlock *UseBlock = UseInst->getParent();
189    if (!(UseBlock == MBB && UseInst->isPHI() &&
190          UseInst->getOperand(I.getOperandNo()+1).getMBB() == DefMBB)) {
191      BreakPHIEdge = false;
192      break;
193    }
194  }
195  if (BreakPHIEdge)
196    return true;
197
198  for (MachineRegisterInfo::use_nodbg_iterator
199         I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
200       I != E; ++I) {
201    // Determine the block of the use.
202    MachineInstr *UseInst = &*I;
203    MachineBasicBlock *UseBlock = UseInst->getParent();
204    if (UseInst->isPHI()) {
205      // PHI nodes use the operand in the predecessor block, not the block with
206      // the PHI.
207      UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
208    } else if (UseBlock == DefMBB) {
209      LocalUse = true;
210      return false;
211    }
212
213    // Check that it dominates.
214    if (!DT->dominates(MBB, UseBlock))
215      return false;
216  }
217
218  return true;
219}
220
221bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
222  DEBUG(dbgs() << "******** Machine Sinking ********\n");
223
224  const TargetMachine &TM = MF.getTarget();
225  TII = TM.getInstrInfo();
226  TRI = TM.getRegisterInfo();
227  MRI = &MF.getRegInfo();
228  DT = &getAnalysis<MachineDominatorTree>();
229  LI = &getAnalysis<MachineLoopInfo>();
230  AA = &getAnalysis<AliasAnalysis>();
231
232  bool EverMadeChange = false;
233
234  while (1) {
235    bool MadeChange = false;
236
237    // Process all basic blocks.
238    CEBCandidates.clear();
239    for (MachineFunction::iterator I = MF.begin(), E = MF.end();
240         I != E; ++I)
241      MadeChange |= ProcessBlock(*I);
242
243    // If this iteration over the code changed anything, keep iterating.
244    if (!MadeChange) break;
245    EverMadeChange = true;
246  }
247  return EverMadeChange;
248}
249
250bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
251  // Can't sink anything out of a block that has less than two successors.
252  if (MBB.succ_size() <= 1 || MBB.empty()) return false;
253
254  // Don't bother sinking code out of unreachable blocks. In addition to being
255  // unprofitable, it can also lead to infinite looping, because in an
256  // unreachable loop there may be nowhere to stop.
257  if (!DT->isReachableFromEntry(&MBB)) return false;
258
259  bool MadeChange = false;
260
261  // Walk the basic block bottom-up.  Remember if we saw a store.
262  MachineBasicBlock::iterator I = MBB.end();
263  --I;
264  bool ProcessedBegin, SawStore = false;
265  do {
266    MachineInstr *MI = I;  // The instruction to sink.
267
268    // Predecrement I (if it's not begin) so that it isn't invalidated by
269    // sinking.
270    ProcessedBegin = I == MBB.begin();
271    if (!ProcessedBegin)
272      --I;
273
274    if (MI->isDebugValue())
275      continue;
276
277    bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
278    if (Joined) {
279      MadeChange = true;
280      continue;
281    }
282
283    if (SinkInstruction(MI, SawStore))
284      ++NumSunk, MadeChange = true;
285
286    // If we just processed the first instruction in the block, we're done.
287  } while (!ProcessedBegin);
288
289  return MadeChange;
290}
291
292bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr *MI,
293                                                 MachineBasicBlock *From,
294                                                 MachineBasicBlock *To) {
295  // FIXME: Need much better heuristics.
296
297  // If the pass has already considered breaking this edge (during this pass
298  // through the function), then let's go ahead and break it. This means
299  // sinking multiple "cheap" instructions into the same block.
300  if (!CEBCandidates.insert(std::make_pair(From, To)))
301    return true;
302
303  if (!MI->isCopy() && !MI->isAsCheapAsAMove())
304    return true;
305
306  // MI is cheap, we probably don't want to break the critical edge for it.
307  // However, if this would allow some definitions of its source operands
308  // to be sunk then it's probably worth it.
309  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
310    const MachineOperand &MO = MI->getOperand(i);
311    if (!MO.isReg() || !MO.isUse())
312      continue;
313    unsigned Reg = MO.getReg();
314    if (Reg == 0)
315      continue;
316
317    // We don't move live definitions of physical registers,
318    // so sinking their uses won't enable any opportunities.
319    if (TargetRegisterInfo::isPhysicalRegister(Reg))
320      continue;
321
322    // If this instruction is the only user of a virtual register,
323    // check if breaking the edge will enable sinking
324    // both this instruction and the defining instruction.
325    if (MRI->hasOneNonDBGUse(Reg)) {
326      // If the definition resides in same MBB,
327      // claim it's likely we can sink these together.
328      // If definition resides elsewhere, we aren't
329      // blocking it from being sunk so don't break the edge.
330      MachineInstr *DefMI = MRI->getVRegDef(Reg);
331      if (DefMI->getParent() == MI->getParent())
332        return true;
333    }
334  }
335
336  return false;
337}
338
339MachineBasicBlock *MachineSinking::SplitCriticalEdge(MachineInstr *MI,
340                                                     MachineBasicBlock *FromBB,
341                                                     MachineBasicBlock *ToBB,
342                                                     bool BreakPHIEdge) {
343  if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
344    return 0;
345
346  // Avoid breaking back edge. From == To means backedge for single BB loop.
347  if (!SplitEdges || FromBB == ToBB)
348    return 0;
349
350  // Check for backedges of more "complex" loops.
351  if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
352      LI->isLoopHeader(ToBB))
353    return 0;
354
355  // It's not always legal to break critical edges and sink the computation
356  // to the edge.
357  //
358  // BB#1:
359  // v1024
360  // Beq BB#3
361  // <fallthrough>
362  // BB#2:
363  // ... no uses of v1024
364  // <fallthrough>
365  // BB#3:
366  // ...
367  //       = v1024
368  //
369  // If BB#1 -> BB#3 edge is broken and computation of v1024 is inserted:
370  //
371  // BB#1:
372  // ...
373  // Bne BB#2
374  // BB#4:
375  // v1024 =
376  // B BB#3
377  // BB#2:
378  // ... no uses of v1024
379  // <fallthrough>
380  // BB#3:
381  // ...
382  //       = v1024
383  //
384  // This is incorrect since v1024 is not computed along the BB#1->BB#2->BB#3
385  // flow. We need to ensure the new basic block where the computation is
386  // sunk to dominates all the uses.
387  // It's only legal to break critical edge and sink the computation to the
388  // new block if all the predecessors of "To", except for "From", are
389  // not dominated by "From". Given SSA property, this means these
390  // predecessors are dominated by "To".
391  //
392  // There is no need to do this check if all the uses are PHI nodes. PHI
393  // sources are only defined on the specific predecessor edges.
394  if (!BreakPHIEdge) {
395    for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
396           E = ToBB->pred_end(); PI != E; ++PI) {
397      if (*PI == FromBB)
398        continue;
399      if (!DT->dominates(ToBB, *PI))
400        return 0;
401    }
402  }
403
404  return FromBB->SplitCriticalEdge(ToBB, this);
405}
406
407static bool AvoidsSinking(MachineInstr *MI, MachineRegisterInfo *MRI) {
408  return MI->isInsertSubreg() || MI->isSubregToReg() || MI->isRegSequence();
409}
410
411/// collectDebgValues - Scan instructions following MI and collect any
412/// matching DBG_VALUEs.
413static void collectDebugValues(MachineInstr *MI,
414                               SmallVectorImpl<MachineInstr *> &DbgValues) {
415  DbgValues.clear();
416  if (!MI->getOperand(0).isReg())
417    return;
418
419  MachineBasicBlock::iterator DI = MI; ++DI;
420  for (MachineBasicBlock::iterator DE = MI->getParent()->end();
421       DI != DE; ++DI) {
422    if (!DI->isDebugValue())
423      return;
424    if (DI->getOperand(0).isReg() &&
425        DI->getOperand(0).getReg() == MI->getOperand(0).getReg())
426      DbgValues.push_back(DI);
427  }
428}
429
430/// isPostDominatedBy - Return true if A is post dominated by B.
431static bool isPostDominatedBy(MachineBasicBlock *A, MachineBasicBlock *B) {
432
433  // FIXME - Use real post dominator.
434  if (A->succ_size() != 2)
435    return false;
436  MachineBasicBlock::succ_iterator I = A->succ_begin();
437  if (B == *I)
438    ++I;
439  MachineBasicBlock *OtherSuccBlock = *I;
440  if (OtherSuccBlock->succ_size() != 1 ||
441      *(OtherSuccBlock->succ_begin()) != B)
442    return false;
443
444  return true;
445}
446
447/// isProfitableToSinkTo - Return true if it is profitable to sink MI.
448bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
449                                          MachineBasicBlock *MBB,
450                                          MachineBasicBlock *SuccToSinkTo) {
451  assert (MI && "Invalid MachineInstr!");
452  assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
453
454  if (MBB == SuccToSinkTo)
455    return false;
456
457  // It is profitable if SuccToSinkTo does not post dominate current block.
458  if (!isPostDominatedBy(MBB, SuccToSinkTo))
459      return true;
460
461  // Check if only use in post dominated block is PHI instruction.
462  bool NonPHIUse = false;
463  for (MachineRegisterInfo::use_nodbg_iterator
464         I = MRI->use_nodbg_begin(Reg), E = MRI->use_nodbg_end();
465       I != E; ++I) {
466    MachineInstr *UseInst = &*I;
467    MachineBasicBlock *UseBlock = UseInst->getParent();
468    if (UseBlock == SuccToSinkTo && !UseInst->isPHI())
469      NonPHIUse = true;
470  }
471  if (!NonPHIUse)
472    return true;
473
474  // If SuccToSinkTo post dominates then also it may be profitable if MI
475  // can further profitably sinked into another block in next round.
476  bool BreakPHIEdge = false;
477  // FIXME - If finding successor is compile time expensive then catch results.
478  if (MachineBasicBlock *MBB2 = FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge))
479    return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2);
480
481  // If SuccToSinkTo is final destination and it is a post dominator of current
482  // block then it is not profitable to sink MI into SuccToSinkTo block.
483  return false;
484}
485
486/// FindSuccToSinkTo - Find a successor to sink this instruction to.
487MachineBasicBlock *MachineSinking::FindSuccToSinkTo(MachineInstr *MI,
488                                   MachineBasicBlock *MBB,
489                                   bool &BreakPHIEdge) {
490
491  assert (MI && "Invalid MachineInstr!");
492  assert (MBB && "Invalid MachineBasicBlock!");
493
494  // Loop over all the operands of the specified instruction.  If there is
495  // anything we can't handle, bail out.
496
497  // SuccToSinkTo - This is the successor to sink this instruction to, once we
498  // decide.
499  MachineBasicBlock *SuccToSinkTo = 0;
500  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
501    const MachineOperand &MO = MI->getOperand(i);
502    if (!MO.isReg()) continue;  // Ignore non-register operands.
503
504    unsigned Reg = MO.getReg();
505    if (Reg == 0) continue;
506
507    if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
508      if (MO.isUse()) {
509        // If the physreg has no defs anywhere, it's just an ambient register
510        // and we can freely move its uses. Alternatively, if it's allocatable,
511        // it could get allocated to something with a def during allocation.
512        if (!MRI->isConstantPhysReg(Reg, *MBB->getParent()))
513          return NULL;
514      } else if (!MO.isDead()) {
515        // A def that isn't dead. We can't move it.
516        return NULL;
517      }
518    } else {
519      // Virtual register uses are always safe to sink.
520      if (MO.isUse()) continue;
521
522      // If it's not safe to move defs of the register class, then abort.
523      if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
524        return NULL;
525
526      // FIXME: This picks a successor to sink into based on having one
527      // successor that dominates all the uses.  However, there are cases where
528      // sinking can happen but where the sink point isn't a successor.  For
529      // example:
530      //
531      //   x = computation
532      //   if () {} else {}
533      //   use x
534      //
535      // the instruction could be sunk over the whole diamond for the
536      // if/then/else (or loop, etc), allowing it to be sunk into other blocks
537      // after that.
538
539      // Virtual register defs can only be sunk if all their uses are in blocks
540      // dominated by one of the successors.
541      if (SuccToSinkTo) {
542        // If a previous operand picked a block to sink to, then this operand
543        // must be sinkable to the same block.
544        bool LocalUse = false;
545        if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
546                                     BreakPHIEdge, LocalUse))
547          return NULL;
548
549        continue;
550      }
551
552      // Otherwise, we should look at all the successors and decide which one
553      // we should sink to.
554      // We give successors with smaller loop depth higher priority.
555      SmallVector<MachineBasicBlock*, 4> Succs(MBB->succ_begin(), MBB->succ_end());
556      std::stable_sort(Succs.begin(), Succs.end(), SuccessorSorter(LI));
557      for (SmallVectorImpl<MachineBasicBlock *>::iterator SI = Succs.begin(),
558             E = Succs.end(); SI != E; ++SI) {
559        MachineBasicBlock *SuccBlock = *SI;
560        bool LocalUse = false;
561        if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
562                                    BreakPHIEdge, LocalUse)) {
563          SuccToSinkTo = SuccBlock;
564          break;
565        }
566        if (LocalUse)
567          // Def is used locally, it's never safe to move this def.
568          return NULL;
569      }
570
571      // If we couldn't find a block to sink to, ignore this instruction.
572      if (SuccToSinkTo == 0)
573        return NULL;
574      else if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo))
575        return NULL;
576    }
577  }
578
579  // It is not possible to sink an instruction into its own block.  This can
580  // happen with loops.
581  if (MBB == SuccToSinkTo)
582    return NULL;
583
584  // It's not safe to sink instructions to EH landing pad. Control flow into
585  // landing pad is implicitly defined.
586  if (SuccToSinkTo && SuccToSinkTo->isLandingPad())
587    return NULL;
588
589  return SuccToSinkTo;
590}
591
592/// SinkInstruction - Determine whether it is safe to sink the specified machine
593/// instruction out of its current block into a successor.
594bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
595  // Don't sink insert_subreg, subreg_to_reg, reg_sequence. These are meant to
596  // be close to the source to make it easier to coalesce.
597  if (AvoidsSinking(MI, MRI))
598    return false;
599
600  // Check if it's safe to move the instruction.
601  if (!MI->isSafeToMove(TII, AA, SawStore))
602    return false;
603
604  // FIXME: This should include support for sinking instructions within the
605  // block they are currently in to shorten the live ranges.  We often get
606  // instructions sunk into the top of a large block, but it would be better to
607  // also sink them down before their first use in the block.  This xform has to
608  // be careful not to *increase* register pressure though, e.g. sinking
609  // "x = y + z" down if it kills y and z would increase the live ranges of y
610  // and z and only shrink the live range of x.
611
612  bool BreakPHIEdge = false;
613  MachineBasicBlock *ParentBlock = MI->getParent();
614  MachineBasicBlock *SuccToSinkTo = FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge);
615
616  // If there are no outputs, it must have side-effects.
617  if (SuccToSinkTo == 0)
618    return false;
619
620
621  // If the instruction to move defines a dead physical register which is live
622  // when leaving the basic block, don't move it because it could turn into a
623  // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
624  for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
625    const MachineOperand &MO = MI->getOperand(I);
626    if (!MO.isReg()) continue;
627    unsigned Reg = MO.getReg();
628    if (Reg == 0 || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
629    if (SuccToSinkTo->isLiveIn(Reg))
630      return false;
631  }
632
633  DEBUG(dbgs() << "Sink instr " << *MI << "\tinto block " << *SuccToSinkTo);
634
635  // If the block has multiple predecessors, this is a critical edge.
636  // Decide if we can sink along it or need to break the edge.
637  if (SuccToSinkTo->pred_size() > 1) {
638    // We cannot sink a load across a critical edge - there may be stores in
639    // other code paths.
640    bool TryBreak = false;
641    bool store = true;
642    if (!MI->isSafeToMove(TII, AA, store)) {
643      DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
644      TryBreak = true;
645    }
646
647    // We don't want to sink across a critical edge if we don't dominate the
648    // successor. We could be introducing calculations to new code paths.
649    if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
650      DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
651      TryBreak = true;
652    }
653
654    // Don't sink instructions into a loop.
655    if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
656      DEBUG(dbgs() << " *** NOTE: Loop header found\n");
657      TryBreak = true;
658    }
659
660    // Otherwise we are OK with sinking along a critical edge.
661    if (!TryBreak)
662      DEBUG(dbgs() << "Sinking along critical edge.\n");
663    else {
664      MachineBasicBlock *NewSucc =
665        SplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
666      if (!NewSucc) {
667        DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
668                        "break critical edge\n");
669        return false;
670      } else {
671        DEBUG(dbgs() << " *** Splitting critical edge:"
672              " BB#" << ParentBlock->getNumber()
673              << " -- BB#" << NewSucc->getNumber()
674              << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
675        SuccToSinkTo = NewSucc;
676        ++NumSplit;
677        BreakPHIEdge = false;
678      }
679    }
680  }
681
682  if (BreakPHIEdge) {
683    // BreakPHIEdge is true if all the uses are in the successor MBB being
684    // sunken into and they are all PHI nodes. In this case, machine-sink must
685    // break the critical edge first.
686    MachineBasicBlock *NewSucc = SplitCriticalEdge(MI, ParentBlock,
687                                                   SuccToSinkTo, BreakPHIEdge);
688    if (!NewSucc) {
689      DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
690            "break critical edge\n");
691      return false;
692    }
693
694    DEBUG(dbgs() << " *** Splitting critical edge:"
695          " BB#" << ParentBlock->getNumber()
696          << " -- BB#" << NewSucc->getNumber()
697          << " -- BB#" << SuccToSinkTo->getNumber() << '\n');
698    SuccToSinkTo = NewSucc;
699    ++NumSplit;
700  }
701
702  // Determine where to insert into. Skip phi nodes.
703  MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
704  while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
705    ++InsertPos;
706
707  // collect matching debug values.
708  SmallVector<MachineInstr *, 2> DbgValuesToSink;
709  collectDebugValues(MI, DbgValuesToSink);
710
711  // Move the instruction.
712  SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
713                       ++MachineBasicBlock::iterator(MI));
714
715  // Move debug values.
716  for (SmallVectorImpl<MachineInstr *>::iterator DBI = DbgValuesToSink.begin(),
717         DBE = DbgValuesToSink.end(); DBI != DBE; ++DBI) {
718    MachineInstr *DbgMI = *DBI;
719    SuccToSinkTo->splice(InsertPos, ParentBlock,  DbgMI,
720                         ++MachineBasicBlock::iterator(DbgMI));
721  }
722
723  // Conservatively, clear any kill flags, since it's possible that they are no
724  // longer correct.
725  MI->clearKillInfo();
726
727  return true;
728}
729