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