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