1 //===- MachineSink.cpp - Sinking for machine instructions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass moves instructions into successor blocks when possible, so that
10 // they aren't executed on paths where their results aren't needed.
11 //
12 // This pass is not intended to be a replacement or a complete alternative
13 // for an LLVM-IR-level sinking pass. It is only designed to sink simple
14 // constructs that are not exposed before lowering and instruction selection.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/PointerIntPair.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/SparseBitVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/CodeGen/MachineBasicBlock.h"
27 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
28 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
29 #include "llvm/CodeGen/MachineDominators.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineLoopInfo.h"
34 #include "llvm/CodeGen/MachineOperand.h"
35 #include "llvm/CodeGen/MachinePostDominators.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/TargetInstrInfo.h"
38 #include "llvm/CodeGen/TargetRegisterInfo.h"
39 #include "llvm/CodeGen/TargetSubtargetInfo.h"
40 #include "llvm/IR/BasicBlock.h"
41 #include "llvm/IR/DebugInfoMetadata.h"
42 #include "llvm/IR/LLVMContext.h"
43 #include "llvm/InitializePasses.h"
44 #include "llvm/MC/MCRegisterInfo.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/BranchProbability.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include <algorithm>
51 #include <cassert>
52 #include <cstdint>
53 #include <map>
54 #include <utility>
55 #include <vector>
56 
57 using namespace llvm;
58 
59 #define DEBUG_TYPE "machine-sink"
60 
61 static cl::opt<bool>
62 SplitEdges("machine-sink-split",
63            cl::desc("Split critical edges during machine sinking"),
64            cl::init(true), cl::Hidden);
65 
66 static cl::opt<bool>
67 UseBlockFreqInfo("machine-sink-bfi",
68            cl::desc("Use block frequency info to find successors to sink"),
69            cl::init(true), cl::Hidden);
70 
71 static cl::opt<unsigned> SplitEdgeProbabilityThreshold(
72     "machine-sink-split-probability-threshold",
73     cl::desc(
74         "Percentage threshold for splitting single-instruction critical edge. "
75         "If the branch threshold is higher than this threshold, we allow "
76         "speculative execution of up to 1 instruction to avoid branching to "
77         "splitted critical edge"),
78     cl::init(40), cl::Hidden);
79 
80 STATISTIC(NumSunk,      "Number of machine instructions sunk");
81 STATISTIC(NumSplit,     "Number of critical edges split");
82 STATISTIC(NumCoalesces, "Number of copies coalesced");
83 STATISTIC(NumPostRACopySink, "Number of copies sunk after RA");
84 
85 namespace {
86 
87   class MachineSinking : public MachineFunctionPass {
88     const TargetInstrInfo *TII;
89     const TargetRegisterInfo *TRI;
90     MachineRegisterInfo  *MRI;     // Machine register information
91     MachineDominatorTree *DT;      // Machine dominator tree
92     MachinePostDominatorTree *PDT; // Machine post dominator tree
93     MachineLoopInfo *LI;
94     MachineBlockFrequencyInfo *MBFI;
95     const MachineBranchProbabilityInfo *MBPI;
96     AliasAnalysis *AA;
97 
98     // Remember which edges have been considered for breaking.
99     SmallSet<std::pair<MachineBasicBlock*, MachineBasicBlock*>, 8>
100     CEBCandidates;
101     // Remember which edges we are about to split.
102     // This is different from CEBCandidates since those edges
103     // will be split.
104     SetVector<std::pair<MachineBasicBlock *, MachineBasicBlock *>> ToSplit;
105 
106     SparseBitVector<> RegsToClearKillFlags;
107 
108     using AllSuccsCache =
109         std::map<MachineBasicBlock *, SmallVector<MachineBasicBlock *, 4>>;
110 
111     /// DBG_VALUE pointer and flag. The flag is true if this DBG_VALUE is
112     /// post-dominated by another DBG_VALUE of the same variable location.
113     /// This is necessary to detect sequences such as:
114     ///     %0 = someinst
115     ///     DBG_VALUE %0, !123, !DIExpression()
116     ///     %1 = anotherinst
117     ///     DBG_VALUE %1, !123, !DIExpression()
118     /// Where if %0 were to sink, the DBG_VAUE should not sink with it, as that
119     /// would re-order assignments.
120     using SeenDbgUser = PointerIntPair<MachineInstr *, 1>;
121 
122     /// Record of DBG_VALUE uses of vregs in a block, so that we can identify
123     /// debug instructions to sink.
124     SmallDenseMap<unsigned, TinyPtrVector<SeenDbgUser>> SeenDbgUsers;
125 
126     /// Record of debug variables that have had their locations set in the
127     /// current block.
128     DenseSet<DebugVariable> SeenDbgVars;
129 
130   public:
131     static char ID; // Pass identification
132 
133     MachineSinking() : MachineFunctionPass(ID) {
134       initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
135     }
136 
137     bool runOnMachineFunction(MachineFunction &MF) override;
138 
139     void getAnalysisUsage(AnalysisUsage &AU) const override {
140       MachineFunctionPass::getAnalysisUsage(AU);
141       AU.addRequired<AAResultsWrapperPass>();
142       AU.addRequired<MachineDominatorTree>();
143       AU.addRequired<MachinePostDominatorTree>();
144       AU.addRequired<MachineLoopInfo>();
145       AU.addRequired<MachineBranchProbabilityInfo>();
146       AU.addPreserved<MachineLoopInfo>();
147       if (UseBlockFreqInfo)
148         AU.addRequired<MachineBlockFrequencyInfo>();
149     }
150 
151     void releaseMemory() override {
152       CEBCandidates.clear();
153     }
154 
155   private:
156     bool ProcessBlock(MachineBasicBlock &MBB);
157     void ProcessDbgInst(MachineInstr &MI);
158     bool isWorthBreakingCriticalEdge(MachineInstr &MI,
159                                      MachineBasicBlock *From,
160                                      MachineBasicBlock *To);
161 
162     /// Postpone the splitting of the given critical
163     /// edge (\p From, \p To).
164     ///
165     /// We do not split the edges on the fly. Indeed, this invalidates
166     /// the dominance information and thus triggers a lot of updates
167     /// of that information underneath.
168     /// Instead, we postpone all the splits after each iteration of
169     /// the main loop. That way, the information is at least valid
170     /// for the lifetime of an iteration.
171     ///
172     /// \return True if the edge is marked as toSplit, false otherwise.
173     /// False can be returned if, for instance, this is not profitable.
174     bool PostponeSplitCriticalEdge(MachineInstr &MI,
175                                    MachineBasicBlock *From,
176                                    MachineBasicBlock *To,
177                                    bool BreakPHIEdge);
178     bool SinkInstruction(MachineInstr &MI, bool &SawStore,
179                          AllSuccsCache &AllSuccessors);
180 
181     /// If we sink a COPY inst, some debug users of it's destination may no
182     /// longer be dominated by the COPY, and will eventually be dropped.
183     /// This is easily rectified by forwarding the non-dominated debug uses
184     /// to the copy source.
185     void SalvageUnsunkDebugUsersOfCopy(MachineInstr &,
186                                        MachineBasicBlock *TargetBlock);
187     bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
188                                  MachineBasicBlock *DefMBB,
189                                  bool &BreakPHIEdge, bool &LocalUse) const;
190     MachineBasicBlock *FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
191                bool &BreakPHIEdge, AllSuccsCache &AllSuccessors);
192     bool isProfitableToSinkTo(unsigned Reg, MachineInstr &MI,
193                               MachineBasicBlock *MBB,
194                               MachineBasicBlock *SuccToSinkTo,
195                               AllSuccsCache &AllSuccessors);
196 
197     bool PerformTrivialForwardCoalescing(MachineInstr &MI,
198                                          MachineBasicBlock *MBB);
199 
200     SmallVector<MachineBasicBlock *, 4> &
201     GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
202                            AllSuccsCache &AllSuccessors) const;
203   };
204 
205 } // end anonymous namespace
206 
207 char MachineSinking::ID = 0;
208 
209 char &llvm::MachineSinkingID = MachineSinking::ID;
210 
211 INITIALIZE_PASS_BEGIN(MachineSinking, DEBUG_TYPE,
212                       "Machine code sinking", false, false)
213 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
214 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
215 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
216 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
217 INITIALIZE_PASS_END(MachineSinking, DEBUG_TYPE,
218                     "Machine code sinking", false, false)
219 
220 bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr &MI,
221                                                      MachineBasicBlock *MBB) {
222   if (!MI.isCopy())
223     return false;
224 
225   Register SrcReg = MI.getOperand(1).getReg();
226   Register DstReg = MI.getOperand(0).getReg();
227   if (!Register::isVirtualRegister(SrcReg) ||
228       !Register::isVirtualRegister(DstReg) || !MRI->hasOneNonDBGUse(SrcReg))
229     return false;
230 
231   const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
232   const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
233   if (SRC != DRC)
234     return false;
235 
236   MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
237   if (DefMI->isCopyLike())
238     return false;
239   LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI);
240   LLVM_DEBUG(dbgs() << "*** to: " << MI);
241   MRI->replaceRegWith(DstReg, SrcReg);
242   MI.eraseFromParent();
243 
244   // Conservatively, clear any kill flags, since it's possible that they are no
245   // longer correct.
246   MRI->clearKillFlags(SrcReg);
247 
248   ++NumCoalesces;
249   return true;
250 }
251 
252 /// AllUsesDominatedByBlock - Return true if all uses of the specified register
253 /// occur in blocks dominated by the specified block. If any use is in the
254 /// definition block, then return false since it is never legal to move def
255 /// after uses.
256 bool
257 MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
258                                         MachineBasicBlock *MBB,
259                                         MachineBasicBlock *DefMBB,
260                                         bool &BreakPHIEdge,
261                                         bool &LocalUse) const {
262   assert(Register::isVirtualRegister(Reg) && "Only makes sense for vregs");
263 
264   // Ignore debug uses because debug info doesn't affect the code.
265   if (MRI->use_nodbg_empty(Reg))
266     return true;
267 
268   // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
269   // into and they are all PHI nodes. In this case, machine-sink must break
270   // the critical edge first. e.g.
271   //
272   // %bb.1: derived from LLVM BB %bb4.preheader
273   //   Predecessors according to CFG: %bb.0
274   //     ...
275   //     %reg16385 = DEC64_32r %reg16437, implicit-def dead %eflags
276   //     ...
277   //     JE_4 <%bb.37>, implicit %eflags
278   //   Successors according to CFG: %bb.37 %bb.2
279   //
280   // %bb.2: derived from LLVM BB %bb.nph
281   //   Predecessors according to CFG: %bb.0 %bb.1
282   //     %reg16386 = PHI %reg16434, %bb.0, %reg16385, %bb.1
283   BreakPHIEdge = true;
284   for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
285     MachineInstr *UseInst = MO.getParent();
286     unsigned OpNo = &MO - &UseInst->getOperand(0);
287     MachineBasicBlock *UseBlock = UseInst->getParent();
288     if (!(UseBlock == MBB && UseInst->isPHI() &&
289           UseInst->getOperand(OpNo+1).getMBB() == DefMBB)) {
290       BreakPHIEdge = false;
291       break;
292     }
293   }
294   if (BreakPHIEdge)
295     return true;
296 
297   for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
298     // Determine the block of the use.
299     MachineInstr *UseInst = MO.getParent();
300     unsigned OpNo = &MO - &UseInst->getOperand(0);
301     MachineBasicBlock *UseBlock = UseInst->getParent();
302     if (UseInst->isPHI()) {
303       // PHI nodes use the operand in the predecessor block, not the block with
304       // the PHI.
305       UseBlock = UseInst->getOperand(OpNo+1).getMBB();
306     } else if (UseBlock == DefMBB) {
307       LocalUse = true;
308       return false;
309     }
310 
311     // Check that it dominates.
312     if (!DT->dominates(MBB, UseBlock))
313       return false;
314   }
315 
316   return true;
317 }
318 
319 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
320   if (skipFunction(MF.getFunction()))
321     return false;
322 
323   LLVM_DEBUG(dbgs() << "******** Machine Sinking ********\n");
324 
325   TII = MF.getSubtarget().getInstrInfo();
326   TRI = MF.getSubtarget().getRegisterInfo();
327   MRI = &MF.getRegInfo();
328   DT = &getAnalysis<MachineDominatorTree>();
329   PDT = &getAnalysis<MachinePostDominatorTree>();
330   LI = &getAnalysis<MachineLoopInfo>();
331   MBFI = UseBlockFreqInfo ? &getAnalysis<MachineBlockFrequencyInfo>() : nullptr;
332   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
333   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
334 
335   bool EverMadeChange = false;
336 
337   while (true) {
338     bool MadeChange = false;
339 
340     // Process all basic blocks.
341     CEBCandidates.clear();
342     ToSplit.clear();
343     for (auto &MBB: MF)
344       MadeChange |= ProcessBlock(MBB);
345 
346     // If we have anything we marked as toSplit, split it now.
347     for (auto &Pair : ToSplit) {
348       auto NewSucc = Pair.first->SplitCriticalEdge(Pair.second, *this);
349       if (NewSucc != nullptr) {
350         LLVM_DEBUG(dbgs() << " *** Splitting critical edge: "
351                           << printMBBReference(*Pair.first) << " -- "
352                           << printMBBReference(*NewSucc) << " -- "
353                           << printMBBReference(*Pair.second) << '\n');
354         if (MBFI) {
355           auto NewSuccFreq = MBFI->getBlockFreq(Pair.first) *
356                              MBPI->getEdgeProbability(Pair.first, NewSucc);
357           MBFI->setBlockFreq(NewSucc, NewSuccFreq.getFrequency());
358         }
359         MadeChange = true;
360         ++NumSplit;
361       } else
362         LLVM_DEBUG(dbgs() << " *** Not legal to break critical edge\n");
363     }
364     // If this iteration over the code changed anything, keep iterating.
365     if (!MadeChange) break;
366     EverMadeChange = true;
367   }
368 
369   // Now clear any kill flags for recorded registers.
370   for (auto I : RegsToClearKillFlags)
371     MRI->clearKillFlags(I);
372   RegsToClearKillFlags.clear();
373 
374   return EverMadeChange;
375 }
376 
377 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
378   // Can't sink anything out of a block that has less than two successors.
379   if (MBB.succ_size() <= 1 || MBB.empty()) return false;
380 
381   // Don't bother sinking code out of unreachable blocks. In addition to being
382   // unprofitable, it can also lead to infinite looping, because in an
383   // unreachable loop there may be nowhere to stop.
384   if (!DT->isReachableFromEntry(&MBB)) return false;
385 
386   bool MadeChange = false;
387 
388   // Cache all successors, sorted by frequency info and loop depth.
389   AllSuccsCache AllSuccessors;
390 
391   // Walk the basic block bottom-up.  Remember if we saw a store.
392   MachineBasicBlock::iterator I = MBB.end();
393   --I;
394   bool ProcessedBegin, SawStore = false;
395   do {
396     MachineInstr &MI = *I;  // The instruction to sink.
397 
398     // Predecrement I (if it's not begin) so that it isn't invalidated by
399     // sinking.
400     ProcessedBegin = I == MBB.begin();
401     if (!ProcessedBegin)
402       --I;
403 
404     if (MI.isDebugInstr()) {
405       if (MI.isDebugValue())
406         ProcessDbgInst(MI);
407       continue;
408     }
409 
410     bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
411     if (Joined) {
412       MadeChange = true;
413       continue;
414     }
415 
416     if (SinkInstruction(MI, SawStore, AllSuccessors)) {
417       ++NumSunk;
418       MadeChange = true;
419     }
420 
421     // If we just processed the first instruction in the block, we're done.
422   } while (!ProcessedBegin);
423 
424   SeenDbgUsers.clear();
425   SeenDbgVars.clear();
426 
427   return MadeChange;
428 }
429 
430 void MachineSinking::ProcessDbgInst(MachineInstr &MI) {
431   // When we see DBG_VALUEs for registers, record any vreg it reads, so that
432   // we know what to sink if the vreg def sinks.
433   assert(MI.isDebugValue() && "Expected DBG_VALUE for processing");
434 
435   DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
436                     MI.getDebugLoc()->getInlinedAt());
437   bool SeenBefore = SeenDbgVars.count(Var) != 0;
438 
439   MachineOperand &MO = MI.getOperand(0);
440   if (MO.isReg() && MO.getReg().isVirtual())
441     SeenDbgUsers[MO.getReg()].push_back(SeenDbgUser(&MI, SeenBefore));
442 
443   // Record the variable for any DBG_VALUE, to avoid re-ordering any of them.
444   SeenDbgVars.insert(Var);
445 }
446 
447 bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr &MI,
448                                                  MachineBasicBlock *From,
449                                                  MachineBasicBlock *To) {
450   // FIXME: Need much better heuristics.
451 
452   // If the pass has already considered breaking this edge (during this pass
453   // through the function), then let's go ahead and break it. This means
454   // sinking multiple "cheap" instructions into the same block.
455   if (!CEBCandidates.insert(std::make_pair(From, To)).second)
456     return true;
457 
458   if (!MI.isCopy() && !TII->isAsCheapAsAMove(MI))
459     return true;
460 
461   if (From->isSuccessor(To) && MBPI->getEdgeProbability(From, To) <=
462       BranchProbability(SplitEdgeProbabilityThreshold, 100))
463     return true;
464 
465   // MI is cheap, we probably don't want to break the critical edge for it.
466   // However, if this would allow some definitions of its source operands
467   // to be sunk then it's probably worth it.
468   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
469     const MachineOperand &MO = MI.getOperand(i);
470     if (!MO.isReg() || !MO.isUse())
471       continue;
472     Register Reg = MO.getReg();
473     if (Reg == 0)
474       continue;
475 
476     // We don't move live definitions of physical registers,
477     // so sinking their uses won't enable any opportunities.
478     if (Register::isPhysicalRegister(Reg))
479       continue;
480 
481     // If this instruction is the only user of a virtual register,
482     // check if breaking the edge will enable sinking
483     // both this instruction and the defining instruction.
484     if (MRI->hasOneNonDBGUse(Reg)) {
485       // If the definition resides in same MBB,
486       // claim it's likely we can sink these together.
487       // If definition resides elsewhere, we aren't
488       // blocking it from being sunk so don't break the edge.
489       MachineInstr *DefMI = MRI->getVRegDef(Reg);
490       if (DefMI->getParent() == MI.getParent())
491         return true;
492     }
493   }
494 
495   return false;
496 }
497 
498 bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr &MI,
499                                                MachineBasicBlock *FromBB,
500                                                MachineBasicBlock *ToBB,
501                                                bool BreakPHIEdge) {
502   if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
503     return false;
504 
505   // Avoid breaking back edge. From == To means backedge for single BB loop.
506   if (!SplitEdges || FromBB == ToBB)
507     return false;
508 
509   // Check for backedges of more "complex" loops.
510   if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
511       LI->isLoopHeader(ToBB))
512     return false;
513 
514   // It's not always legal to break critical edges and sink the computation
515   // to the edge.
516   //
517   // %bb.1:
518   // v1024
519   // Beq %bb.3
520   // <fallthrough>
521   // %bb.2:
522   // ... no uses of v1024
523   // <fallthrough>
524   // %bb.3:
525   // ...
526   //       = v1024
527   //
528   // If %bb.1 -> %bb.3 edge is broken and computation of v1024 is inserted:
529   //
530   // %bb.1:
531   // ...
532   // Bne %bb.2
533   // %bb.4:
534   // v1024 =
535   // B %bb.3
536   // %bb.2:
537   // ... no uses of v1024
538   // <fallthrough>
539   // %bb.3:
540   // ...
541   //       = v1024
542   //
543   // This is incorrect since v1024 is not computed along the %bb.1->%bb.2->%bb.3
544   // flow. We need to ensure the new basic block where the computation is
545   // sunk to dominates all the uses.
546   // It's only legal to break critical edge and sink the computation to the
547   // new block if all the predecessors of "To", except for "From", are
548   // not dominated by "From". Given SSA property, this means these
549   // predecessors are dominated by "To".
550   //
551   // There is no need to do this check if all the uses are PHI nodes. PHI
552   // sources are only defined on the specific predecessor edges.
553   if (!BreakPHIEdge) {
554     for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
555            E = ToBB->pred_end(); PI != E; ++PI) {
556       if (*PI == FromBB)
557         continue;
558       if (!DT->dominates(ToBB, *PI))
559         return false;
560     }
561   }
562 
563   ToSplit.insert(std::make_pair(FromBB, ToBB));
564 
565   return true;
566 }
567 
568 /// isProfitableToSinkTo - Return true if it is profitable to sink MI.
569 bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr &MI,
570                                           MachineBasicBlock *MBB,
571                                           MachineBasicBlock *SuccToSinkTo,
572                                           AllSuccsCache &AllSuccessors) {
573   assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
574 
575   if (MBB == SuccToSinkTo)
576     return false;
577 
578   // It is profitable if SuccToSinkTo does not post dominate current block.
579   if (!PDT->dominates(SuccToSinkTo, MBB))
580     return true;
581 
582   // It is profitable to sink an instruction from a deeper loop to a shallower
583   // loop, even if the latter post-dominates the former (PR21115).
584   if (LI->getLoopDepth(MBB) > LI->getLoopDepth(SuccToSinkTo))
585     return true;
586 
587   // Check if only use in post dominated block is PHI instruction.
588   bool NonPHIUse = false;
589   for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) {
590     MachineBasicBlock *UseBlock = UseInst.getParent();
591     if (UseBlock == SuccToSinkTo && !UseInst.isPHI())
592       NonPHIUse = true;
593   }
594   if (!NonPHIUse)
595     return true;
596 
597   // If SuccToSinkTo post dominates then also it may be profitable if MI
598   // can further profitably sinked into another block in next round.
599   bool BreakPHIEdge = false;
600   // FIXME - If finding successor is compile time expensive then cache results.
601   if (MachineBasicBlock *MBB2 =
602           FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge, AllSuccessors))
603     return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2, AllSuccessors);
604 
605   // If SuccToSinkTo is final destination and it is a post dominator of current
606   // block then it is not profitable to sink MI into SuccToSinkTo block.
607   return false;
608 }
609 
610 /// Get the sorted sequence of successors for this MachineBasicBlock, possibly
611 /// computing it if it was not already cached.
612 SmallVector<MachineBasicBlock *, 4> &
613 MachineSinking::GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
614                                        AllSuccsCache &AllSuccessors) const {
615   // Do we have the sorted successors in cache ?
616   auto Succs = AllSuccessors.find(MBB);
617   if (Succs != AllSuccessors.end())
618     return Succs->second;
619 
620   SmallVector<MachineBasicBlock *, 4> AllSuccs(MBB->succ_begin(),
621                                                MBB->succ_end());
622 
623   // Handle cases where sinking can happen but where the sink point isn't a
624   // successor. For example:
625   //
626   //   x = computation
627   //   if () {} else {}
628   //   use x
629   //
630   const std::vector<MachineDomTreeNode *> &Children =
631     DT->getNode(MBB)->getChildren();
632   for (const auto &DTChild : Children)
633     // DomTree children of MBB that have MBB as immediate dominator are added.
634     if (DTChild->getIDom()->getBlock() == MI.getParent() &&
635         // Skip MBBs already added to the AllSuccs vector above.
636         !MBB->isSuccessor(DTChild->getBlock()))
637       AllSuccs.push_back(DTChild->getBlock());
638 
639   // Sort Successors according to their loop depth or block frequency info.
640   llvm::stable_sort(
641       AllSuccs, [this](const MachineBasicBlock *L, const MachineBasicBlock *R) {
642         uint64_t LHSFreq = MBFI ? MBFI->getBlockFreq(L).getFrequency() : 0;
643         uint64_t RHSFreq = MBFI ? MBFI->getBlockFreq(R).getFrequency() : 0;
644         bool HasBlockFreq = LHSFreq != 0 && RHSFreq != 0;
645         return HasBlockFreq ? LHSFreq < RHSFreq
646                             : LI->getLoopDepth(L) < LI->getLoopDepth(R);
647       });
648 
649   auto it = AllSuccessors.insert(std::make_pair(MBB, AllSuccs));
650 
651   return it.first->second;
652 }
653 
654 /// FindSuccToSinkTo - Find a successor to sink this instruction to.
655 MachineBasicBlock *
656 MachineSinking::FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
657                                  bool &BreakPHIEdge,
658                                  AllSuccsCache &AllSuccessors) {
659   assert (MBB && "Invalid MachineBasicBlock!");
660 
661   // Loop over all the operands of the specified instruction.  If there is
662   // anything we can't handle, bail out.
663 
664   // SuccToSinkTo - This is the successor to sink this instruction to, once we
665   // decide.
666   MachineBasicBlock *SuccToSinkTo = nullptr;
667   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
668     const MachineOperand &MO = MI.getOperand(i);
669     if (!MO.isReg()) continue;  // Ignore non-register operands.
670 
671     Register Reg = MO.getReg();
672     if (Reg == 0) continue;
673 
674     if (Register::isPhysicalRegister(Reg)) {
675       if (MO.isUse()) {
676         // If the physreg has no defs anywhere, it's just an ambient register
677         // and we can freely move its uses. Alternatively, if it's allocatable,
678         // it could get allocated to something with a def during allocation.
679         if (!MRI->isConstantPhysReg(Reg))
680           return nullptr;
681       } else if (!MO.isDead()) {
682         // A def that isn't dead. We can't move it.
683         return nullptr;
684       }
685     } else {
686       // Virtual register uses are always safe to sink.
687       if (MO.isUse()) continue;
688 
689       // If it's not safe to move defs of the register class, then abort.
690       if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
691         return nullptr;
692 
693       // Virtual register defs can only be sunk if all their uses are in blocks
694       // dominated by one of the successors.
695       if (SuccToSinkTo) {
696         // If a previous operand picked a block to sink to, then this operand
697         // must be sinkable to the same block.
698         bool LocalUse = false;
699         if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
700                                      BreakPHIEdge, LocalUse))
701           return nullptr;
702 
703         continue;
704       }
705 
706       // Otherwise, we should look at all the successors and decide which one
707       // we should sink to. If we have reliable block frequency information
708       // (frequency != 0) available, give successors with smaller frequencies
709       // higher priority, otherwise prioritize smaller loop depths.
710       for (MachineBasicBlock *SuccBlock :
711            GetAllSortedSuccessors(MI, MBB, AllSuccessors)) {
712         bool LocalUse = false;
713         if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
714                                     BreakPHIEdge, LocalUse)) {
715           SuccToSinkTo = SuccBlock;
716           break;
717         }
718         if (LocalUse)
719           // Def is used locally, it's never safe to move this def.
720           return nullptr;
721       }
722 
723       // If we couldn't find a block to sink to, ignore this instruction.
724       if (!SuccToSinkTo)
725         return nullptr;
726       if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo, AllSuccessors))
727         return nullptr;
728     }
729   }
730 
731   // It is not possible to sink an instruction into its own block.  This can
732   // happen with loops.
733   if (MBB == SuccToSinkTo)
734     return nullptr;
735 
736   // It's not safe to sink instructions to EH landing pad. Control flow into
737   // landing pad is implicitly defined.
738   if (SuccToSinkTo && SuccToSinkTo->isEHPad())
739     return nullptr;
740 
741   return SuccToSinkTo;
742 }
743 
744 /// Return true if MI is likely to be usable as a memory operation by the
745 /// implicit null check optimization.
746 ///
747 /// This is a "best effort" heuristic, and should not be relied upon for
748 /// correctness.  This returning true does not guarantee that the implicit null
749 /// check optimization is legal over MI, and this returning false does not
750 /// guarantee MI cannot possibly be used to do a null check.
751 static bool SinkingPreventsImplicitNullCheck(MachineInstr &MI,
752                                              const TargetInstrInfo *TII,
753                                              const TargetRegisterInfo *TRI) {
754   using MachineBranchPredicate = TargetInstrInfo::MachineBranchPredicate;
755 
756   auto *MBB = MI.getParent();
757   if (MBB->pred_size() != 1)
758     return false;
759 
760   auto *PredMBB = *MBB->pred_begin();
761   auto *PredBB = PredMBB->getBasicBlock();
762 
763   // Frontends that don't use implicit null checks have no reason to emit
764   // branches with make.implicit metadata, and this function should always
765   // return false for them.
766   if (!PredBB ||
767       !PredBB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit))
768     return false;
769 
770   const MachineOperand *BaseOp;
771   int64_t Offset;
772   bool OffsetIsScalable;
773   if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI))
774     return false;
775 
776   if (!BaseOp->isReg())
777     return false;
778 
779   if (!(MI.mayLoad() && !MI.isPredicable()))
780     return false;
781 
782   MachineBranchPredicate MBP;
783   if (TII->analyzeBranchPredicate(*PredMBB, MBP, false))
784     return false;
785 
786   return MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
787          (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
788           MBP.Predicate == MachineBranchPredicate::PRED_EQ) &&
789          MBP.LHS.getReg() == BaseOp->getReg();
790 }
791 
792 /// If the sunk instruction is a copy, try to forward the copy instead of
793 /// leaving an 'undef' DBG_VALUE in the original location. Don't do this if
794 /// there's any subregister weirdness involved. Returns true if copy
795 /// propagation occurred.
796 static bool attemptDebugCopyProp(MachineInstr &SinkInst, MachineInstr &DbgMI) {
797   const MachineRegisterInfo &MRI = SinkInst.getMF()->getRegInfo();
798   const TargetInstrInfo &TII = *SinkInst.getMF()->getSubtarget().getInstrInfo();
799 
800   // Copy DBG_VALUE operand and set the original to undef. We then check to
801   // see whether this is something that can be copy-forwarded. If it isn't,
802   // continue around the loop.
803   MachineOperand DbgMO = DbgMI.getOperand(0);
804 
805   const MachineOperand *SrcMO = nullptr, *DstMO = nullptr;
806   auto CopyOperands = TII.isCopyInstr(SinkInst);
807   if (!CopyOperands)
808     return false;
809   SrcMO = CopyOperands->Source;
810   DstMO = CopyOperands->Destination;
811 
812   // Check validity of forwarding this copy.
813   bool PostRA = MRI.getNumVirtRegs() == 0;
814 
815   // Trying to forward between physical and virtual registers is too hard.
816   if (DbgMO.getReg().isVirtual() != SrcMO->getReg().isVirtual())
817     return false;
818 
819   // Only try virtual register copy-forwarding before regalloc, and physical
820   // register copy-forwarding after regalloc.
821   bool arePhysRegs = !DbgMO.getReg().isVirtual();
822   if (arePhysRegs != PostRA)
823     return false;
824 
825   // Pre-regalloc, only forward if all subregisters agree (or there are no
826   // subregs at all). More analysis might recover some forwardable copies.
827   if (!PostRA && (DbgMO.getSubReg() != SrcMO->getSubReg() ||
828                   DbgMO.getSubReg() != DstMO->getSubReg()))
829     return false;
830 
831   // Post-regalloc, we may be sinking a DBG_VALUE of a sub or super-register
832   // of this copy. Only forward the copy if the DBG_VALUE operand exactly
833   // matches the copy destination.
834   if (PostRA && DbgMO.getReg() != DstMO->getReg())
835     return false;
836 
837   DbgMI.getOperand(0).setReg(SrcMO->getReg());
838   DbgMI.getOperand(0).setSubReg(SrcMO->getSubReg());
839   return true;
840 }
841 
842 /// Sink an instruction and its associated debug instructions.
843 static void performSink(MachineInstr &MI, MachineBasicBlock &SuccToSinkTo,
844                         MachineBasicBlock::iterator InsertPos,
845                         SmallVectorImpl<MachineInstr *> &DbgValuesToSink) {
846 
847   // If we cannot find a location to use (merge with), then we erase the debug
848   // location to prevent debug-info driven tools from potentially reporting
849   // wrong location information.
850   if (!SuccToSinkTo.empty() && InsertPos != SuccToSinkTo.end())
851     MI.setDebugLoc(DILocation::getMergedLocation(MI.getDebugLoc(),
852                                                  InsertPos->getDebugLoc()));
853   else
854     MI.setDebugLoc(DebugLoc());
855 
856   // Move the instruction.
857   MachineBasicBlock *ParentBlock = MI.getParent();
858   SuccToSinkTo.splice(InsertPos, ParentBlock, MI,
859                       ++MachineBasicBlock::iterator(MI));
860 
861   // Sink a copy of debug users to the insert position. Mark the original
862   // DBG_VALUE location as 'undef', indicating that any earlier variable
863   // location should be terminated as we've optimised away the value at this
864   // point.
865   for (SmallVectorImpl<MachineInstr *>::iterator DBI = DbgValuesToSink.begin(),
866                                                  DBE = DbgValuesToSink.end();
867        DBI != DBE; ++DBI) {
868     MachineInstr *DbgMI = *DBI;
869     MachineInstr *NewDbgMI = DbgMI->getMF()->CloneMachineInstr(*DBI);
870     SuccToSinkTo.insert(InsertPos, NewDbgMI);
871 
872     if (!attemptDebugCopyProp(MI, *DbgMI))
873       DbgMI->getOperand(0).setReg(0);
874   }
875 }
876 
877 /// SinkInstruction - Determine whether it is safe to sink the specified machine
878 /// instruction out of its current block into a successor.
879 bool MachineSinking::SinkInstruction(MachineInstr &MI, bool &SawStore,
880                                      AllSuccsCache &AllSuccessors) {
881   // Don't sink instructions that the target prefers not to sink.
882   if (!TII->shouldSink(MI))
883     return false;
884 
885   // Check if it's safe to move the instruction.
886   if (!MI.isSafeToMove(AA, SawStore))
887     return false;
888 
889   // Convergent operations may not be made control-dependent on additional
890   // values.
891   if (MI.isConvergent())
892     return false;
893 
894   // Don't break implicit null checks.  This is a performance heuristic, and not
895   // required for correctness.
896   if (SinkingPreventsImplicitNullCheck(MI, TII, TRI))
897     return false;
898 
899   // FIXME: This should include support for sinking instructions within the
900   // block they are currently in to shorten the live ranges.  We often get
901   // instructions sunk into the top of a large block, but it would be better to
902   // also sink them down before their first use in the block.  This xform has to
903   // be careful not to *increase* register pressure though, e.g. sinking
904   // "x = y + z" down if it kills y and z would increase the live ranges of y
905   // and z and only shrink the live range of x.
906 
907   bool BreakPHIEdge = false;
908   MachineBasicBlock *ParentBlock = MI.getParent();
909   MachineBasicBlock *SuccToSinkTo =
910       FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge, AllSuccessors);
911 
912   // If there are no outputs, it must have side-effects.
913   if (!SuccToSinkTo)
914     return false;
915 
916   // If the instruction to move defines a dead physical register which is live
917   // when leaving the basic block, don't move it because it could turn into a
918   // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
919   for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
920     const MachineOperand &MO = MI.getOperand(I);
921     if (!MO.isReg()) continue;
922     Register Reg = MO.getReg();
923     if (Reg == 0 || !Register::isPhysicalRegister(Reg))
924       continue;
925     if (SuccToSinkTo->isLiveIn(Reg))
926       return false;
927   }
928 
929   LLVM_DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccToSinkTo);
930 
931   // If the block has multiple predecessors, this is a critical edge.
932   // Decide if we can sink along it or need to break the edge.
933   if (SuccToSinkTo->pred_size() > 1) {
934     // We cannot sink a load across a critical edge - there may be stores in
935     // other code paths.
936     bool TryBreak = false;
937     bool store = true;
938     if (!MI.isSafeToMove(AA, store)) {
939       LLVM_DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
940       TryBreak = true;
941     }
942 
943     // We don't want to sink across a critical edge if we don't dominate the
944     // successor. We could be introducing calculations to new code paths.
945     if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
946       LLVM_DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
947       TryBreak = true;
948     }
949 
950     // Don't sink instructions into a loop.
951     if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
952       LLVM_DEBUG(dbgs() << " *** NOTE: Loop header found\n");
953       TryBreak = true;
954     }
955 
956     // Otherwise we are OK with sinking along a critical edge.
957     if (!TryBreak)
958       LLVM_DEBUG(dbgs() << "Sinking along critical edge.\n");
959     else {
960       // Mark this edge as to be split.
961       // If the edge can actually be split, the next iteration of the main loop
962       // will sink MI in the newly created block.
963       bool Status =
964         PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
965       if (!Status)
966         LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
967                              "break critical edge\n");
968       // The instruction will not be sunk this time.
969       return false;
970     }
971   }
972 
973   if (BreakPHIEdge) {
974     // BreakPHIEdge is true if all the uses are in the successor MBB being
975     // sunken into and they are all PHI nodes. In this case, machine-sink must
976     // break the critical edge first.
977     bool Status = PostponeSplitCriticalEdge(MI, ParentBlock,
978                                             SuccToSinkTo, BreakPHIEdge);
979     if (!Status)
980       LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
981                            "break critical edge\n");
982     // The instruction will not be sunk this time.
983     return false;
984   }
985 
986   // Determine where to insert into. Skip phi nodes.
987   MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
988   while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
989     ++InsertPos;
990 
991   // Collect debug users of any vreg that this inst defines.
992   SmallVector<MachineInstr *, 4> DbgUsersToSink;
993   for (auto &MO : MI.operands()) {
994     if (!MO.isReg() || !MO.isDef() || !MO.getReg().isVirtual())
995       continue;
996     if (!SeenDbgUsers.count(MO.getReg()))
997       continue;
998 
999     // Sink any users that don't pass any other DBG_VALUEs for this variable.
1000     auto &Users = SeenDbgUsers[MO.getReg()];
1001     for (auto &User : Users) {
1002       MachineInstr *DbgMI = User.getPointer();
1003       if (User.getInt()) {
1004         // This DBG_VALUE would re-order assignments. If we can't copy-propagate
1005         // it, it can't be recovered. Set it undef.
1006         if (!attemptDebugCopyProp(MI, *DbgMI))
1007           DbgMI->getOperand(0).setReg(0);
1008       } else {
1009         DbgUsersToSink.push_back(DbgMI);
1010       }
1011     }
1012   }
1013 
1014   // After sinking, some debug users may not be dominated any more. If possible,
1015   // copy-propagate their operands. As it's expensive, don't do this if there's
1016   // no debuginfo in the program.
1017   if (MI.getMF()->getFunction().getSubprogram() && MI.isCopy())
1018     SalvageUnsunkDebugUsersOfCopy(MI, SuccToSinkTo);
1019 
1020   performSink(MI, *SuccToSinkTo, InsertPos, DbgUsersToSink);
1021 
1022   // Conservatively, clear any kill flags, since it's possible that they are no
1023   // longer correct.
1024   // Note that we have to clear the kill flags for any register this instruction
1025   // uses as we may sink over another instruction which currently kills the
1026   // used registers.
1027   for (MachineOperand &MO : MI.operands()) {
1028     if (MO.isReg() && MO.isUse())
1029       RegsToClearKillFlags.set(MO.getReg()); // Remember to clear kill flags.
1030   }
1031 
1032   return true;
1033 }
1034 
1035 void MachineSinking::SalvageUnsunkDebugUsersOfCopy(
1036     MachineInstr &MI, MachineBasicBlock *TargetBlock) {
1037   assert(MI.isCopy());
1038   assert(MI.getOperand(1).isReg());
1039 
1040   // Enumerate all users of vreg operands that are def'd. Skip those that will
1041   // be sunk. For the rest, if they are not dominated by the block we will sink
1042   // MI into, propagate the copy source to them.
1043   SmallVector<MachineInstr *, 4> DbgDefUsers;
1044   const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1045   for (auto &MO : MI.operands()) {
1046     if (!MO.isReg() || !MO.isDef() || !MO.getReg().isVirtual())
1047       continue;
1048     for (auto &User : MRI.use_instructions(MO.getReg())) {
1049       if (!User.isDebugValue() || DT->dominates(TargetBlock, User.getParent()))
1050         continue;
1051 
1052       // If is in same block, will either sink or be use-before-def.
1053       if (User.getParent() == MI.getParent())
1054         continue;
1055 
1056       assert(User.getOperand(0).isReg() &&
1057              "DBG_VALUE user of vreg, but non reg operand?");
1058       DbgDefUsers.push_back(&User);
1059     }
1060   }
1061 
1062   // Point the users of this copy that are no longer dominated, at the source
1063   // of the copy.
1064   for (auto *User : DbgDefUsers) {
1065     User->getOperand(0).setReg(MI.getOperand(1).getReg());
1066     User->getOperand(0).setSubReg(MI.getOperand(1).getSubReg());
1067   }
1068 }
1069 
1070 //===----------------------------------------------------------------------===//
1071 // This pass is not intended to be a replacement or a complete alternative
1072 // for the pre-ra machine sink pass. It is only designed to sink COPY
1073 // instructions which should be handled after RA.
1074 //
1075 // This pass sinks COPY instructions into a successor block, if the COPY is not
1076 // used in the current block and the COPY is live-in to a single successor
1077 // (i.e., doesn't require the COPY to be duplicated).  This avoids executing the
1078 // copy on paths where their results aren't needed.  This also exposes
1079 // additional opportunites for dead copy elimination and shrink wrapping.
1080 //
1081 // These copies were either not handled by or are inserted after the MachineSink
1082 // pass. As an example of the former case, the MachineSink pass cannot sink
1083 // COPY instructions with allocatable source registers; for AArch64 these type
1084 // of copy instructions are frequently used to move function parameters (PhyReg)
1085 // into virtual registers in the entry block.
1086 //
1087 // For the machine IR below, this pass will sink %w19 in the entry into its
1088 // successor (%bb.1) because %w19 is only live-in in %bb.1.
1089 // %bb.0:
1090 //   %wzr = SUBSWri %w1, 1
1091 //   %w19 = COPY %w0
1092 //   Bcc 11, %bb.2
1093 // %bb.1:
1094 //   Live Ins: %w19
1095 //   BL @fun
1096 //   %w0 = ADDWrr %w0, %w19
1097 //   RET %w0
1098 // %bb.2:
1099 //   %w0 = COPY %wzr
1100 //   RET %w0
1101 // As we sink %w19 (CSR in AArch64) into %bb.1, the shrink-wrapping pass will be
1102 // able to see %bb.0 as a candidate.
1103 //===----------------------------------------------------------------------===//
1104 namespace {
1105 
1106 class PostRAMachineSinking : public MachineFunctionPass {
1107 public:
1108   bool runOnMachineFunction(MachineFunction &MF) override;
1109 
1110   static char ID;
1111   PostRAMachineSinking() : MachineFunctionPass(ID) {}
1112   StringRef getPassName() const override { return "PostRA Machine Sink"; }
1113 
1114   void getAnalysisUsage(AnalysisUsage &AU) const override {
1115     AU.setPreservesCFG();
1116     MachineFunctionPass::getAnalysisUsage(AU);
1117   }
1118 
1119   MachineFunctionProperties getRequiredProperties() const override {
1120     return MachineFunctionProperties().set(
1121         MachineFunctionProperties::Property::NoVRegs);
1122   }
1123 
1124 private:
1125   /// Track which register units have been modified and used.
1126   LiveRegUnits ModifiedRegUnits, UsedRegUnits;
1127 
1128   /// Track DBG_VALUEs of (unmodified) register units. Each DBG_VALUE has an
1129   /// entry in this map for each unit it touches.
1130   DenseMap<unsigned, TinyPtrVector<MachineInstr *>> SeenDbgInstrs;
1131 
1132   /// Sink Copy instructions unused in the same block close to their uses in
1133   /// successors.
1134   bool tryToSinkCopy(MachineBasicBlock &BB, MachineFunction &MF,
1135                      const TargetRegisterInfo *TRI, const TargetInstrInfo *TII);
1136 };
1137 } // namespace
1138 
1139 char PostRAMachineSinking::ID = 0;
1140 char &llvm::PostRAMachineSinkingID = PostRAMachineSinking::ID;
1141 
1142 INITIALIZE_PASS(PostRAMachineSinking, "postra-machine-sink",
1143                 "PostRA Machine Sink", false, false)
1144 
1145 static bool aliasWithRegsInLiveIn(MachineBasicBlock &MBB, unsigned Reg,
1146                                   const TargetRegisterInfo *TRI) {
1147   LiveRegUnits LiveInRegUnits(*TRI);
1148   LiveInRegUnits.addLiveIns(MBB);
1149   return !LiveInRegUnits.available(Reg);
1150 }
1151 
1152 static MachineBasicBlock *
1153 getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
1154                       const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
1155                       unsigned Reg, const TargetRegisterInfo *TRI) {
1156   // Try to find a single sinkable successor in which Reg is live-in.
1157   MachineBasicBlock *BB = nullptr;
1158   for (auto *SI : SinkableBBs) {
1159     if (aliasWithRegsInLiveIn(*SI, Reg, TRI)) {
1160       // If BB is set here, Reg is live-in to at least two sinkable successors,
1161       // so quit.
1162       if (BB)
1163         return nullptr;
1164       BB = SI;
1165     }
1166   }
1167   // Reg is not live-in to any sinkable successors.
1168   if (!BB)
1169     return nullptr;
1170 
1171   // Check if any register aliased with Reg is live-in in other successors.
1172   for (auto *SI : CurBB.successors()) {
1173     if (!SinkableBBs.count(SI) && aliasWithRegsInLiveIn(*SI, Reg, TRI))
1174       return nullptr;
1175   }
1176   return BB;
1177 }
1178 
1179 static MachineBasicBlock *
1180 getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
1181                       const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
1182                       ArrayRef<unsigned> DefedRegsInCopy,
1183                       const TargetRegisterInfo *TRI) {
1184   MachineBasicBlock *SingleBB = nullptr;
1185   for (auto DefReg : DefedRegsInCopy) {
1186     MachineBasicBlock *BB =
1187         getSingleLiveInSuccBB(CurBB, SinkableBBs, DefReg, TRI);
1188     if (!BB || (SingleBB && SingleBB != BB))
1189       return nullptr;
1190     SingleBB = BB;
1191   }
1192   return SingleBB;
1193 }
1194 
1195 static void clearKillFlags(MachineInstr *MI, MachineBasicBlock &CurBB,
1196                            SmallVectorImpl<unsigned> &UsedOpsInCopy,
1197                            LiveRegUnits &UsedRegUnits,
1198                            const TargetRegisterInfo *TRI) {
1199   for (auto U : UsedOpsInCopy) {
1200     MachineOperand &MO = MI->getOperand(U);
1201     Register SrcReg = MO.getReg();
1202     if (!UsedRegUnits.available(SrcReg)) {
1203       MachineBasicBlock::iterator NI = std::next(MI->getIterator());
1204       for (MachineInstr &UI : make_range(NI, CurBB.end())) {
1205         if (UI.killsRegister(SrcReg, TRI)) {
1206           UI.clearRegisterKills(SrcReg, TRI);
1207           MO.setIsKill(true);
1208           break;
1209         }
1210       }
1211     }
1212   }
1213 }
1214 
1215 static void updateLiveIn(MachineInstr *MI, MachineBasicBlock *SuccBB,
1216                          SmallVectorImpl<unsigned> &UsedOpsInCopy,
1217                          SmallVectorImpl<unsigned> &DefedRegsInCopy) {
1218   MachineFunction &MF = *SuccBB->getParent();
1219   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1220   for (unsigned DefReg : DefedRegsInCopy)
1221     for (MCSubRegIterator S(DefReg, TRI, true); S.isValid(); ++S)
1222       SuccBB->removeLiveIn(*S);
1223   for (auto U : UsedOpsInCopy) {
1224     Register SrcReg = MI->getOperand(U).getReg();
1225     LaneBitmask Mask;
1226     for (MCRegUnitMaskIterator S(SrcReg, TRI); S.isValid(); ++S) {
1227       Mask |= (*S).second;
1228     }
1229     SuccBB->addLiveIn(SrcReg, Mask.any() ? Mask : LaneBitmask::getAll());
1230   }
1231   SuccBB->sortUniqueLiveIns();
1232 }
1233 
1234 static bool hasRegisterDependency(MachineInstr *MI,
1235                                   SmallVectorImpl<unsigned> &UsedOpsInCopy,
1236                                   SmallVectorImpl<unsigned> &DefedRegsInCopy,
1237                                   LiveRegUnits &ModifiedRegUnits,
1238                                   LiveRegUnits &UsedRegUnits) {
1239   bool HasRegDependency = false;
1240   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1241     MachineOperand &MO = MI->getOperand(i);
1242     if (!MO.isReg())
1243       continue;
1244     Register Reg = MO.getReg();
1245     if (!Reg)
1246       continue;
1247     if (MO.isDef()) {
1248       if (!ModifiedRegUnits.available(Reg) || !UsedRegUnits.available(Reg)) {
1249         HasRegDependency = true;
1250         break;
1251       }
1252       DefedRegsInCopy.push_back(Reg);
1253 
1254       // FIXME: instead of isUse(), readsReg() would be a better fix here,
1255       // For example, we can ignore modifications in reg with undef. However,
1256       // it's not perfectly clear if skipping the internal read is safe in all
1257       // other targets.
1258     } else if (MO.isUse()) {
1259       if (!ModifiedRegUnits.available(Reg)) {
1260         HasRegDependency = true;
1261         break;
1262       }
1263       UsedOpsInCopy.push_back(i);
1264     }
1265   }
1266   return HasRegDependency;
1267 }
1268 
1269 static SmallSet<unsigned, 4> getRegUnits(unsigned Reg,
1270                                          const TargetRegisterInfo *TRI) {
1271   SmallSet<unsigned, 4> RegUnits;
1272   for (auto RI = MCRegUnitIterator(Reg, TRI); RI.isValid(); ++RI)
1273     RegUnits.insert(*RI);
1274   return RegUnits;
1275 }
1276 
1277 bool PostRAMachineSinking::tryToSinkCopy(MachineBasicBlock &CurBB,
1278                                          MachineFunction &MF,
1279                                          const TargetRegisterInfo *TRI,
1280                                          const TargetInstrInfo *TII) {
1281   SmallPtrSet<MachineBasicBlock *, 2> SinkableBBs;
1282   // FIXME: For now, we sink only to a successor which has a single predecessor
1283   // so that we can directly sink COPY instructions to the successor without
1284   // adding any new block or branch instruction.
1285   for (MachineBasicBlock *SI : CurBB.successors())
1286     if (!SI->livein_empty() && SI->pred_size() == 1)
1287       SinkableBBs.insert(SI);
1288 
1289   if (SinkableBBs.empty())
1290     return false;
1291 
1292   bool Changed = false;
1293 
1294   // Track which registers have been modified and used between the end of the
1295   // block and the current instruction.
1296   ModifiedRegUnits.clear();
1297   UsedRegUnits.clear();
1298   SeenDbgInstrs.clear();
1299 
1300   for (auto I = CurBB.rbegin(), E = CurBB.rend(); I != E;) {
1301     MachineInstr *MI = &*I;
1302     ++I;
1303 
1304     // Track the operand index for use in Copy.
1305     SmallVector<unsigned, 2> UsedOpsInCopy;
1306     // Track the register number defed in Copy.
1307     SmallVector<unsigned, 2> DefedRegsInCopy;
1308 
1309     // We must sink this DBG_VALUE if its operand is sunk. To avoid searching
1310     // for DBG_VALUEs later, record them when they're encountered.
1311     if (MI->isDebugValue()) {
1312       auto &MO = MI->getOperand(0);
1313       if (MO.isReg() && Register::isPhysicalRegister(MO.getReg())) {
1314         // Bail if we can already tell the sink would be rejected, rather
1315         // than needlessly accumulating lots of DBG_VALUEs.
1316         if (hasRegisterDependency(MI, UsedOpsInCopy, DefedRegsInCopy,
1317                                   ModifiedRegUnits, UsedRegUnits))
1318           continue;
1319 
1320         // Record debug use of each reg unit.
1321         SmallSet<unsigned, 4> Units = getRegUnits(MO.getReg(), TRI);
1322         for (unsigned Reg : Units)
1323           SeenDbgInstrs[Reg].push_back(MI);
1324       }
1325       continue;
1326     }
1327 
1328     if (MI->isDebugInstr())
1329       continue;
1330 
1331     // Do not move any instruction across function call.
1332     if (MI->isCall())
1333       return false;
1334 
1335     if (!MI->isCopy() || !MI->getOperand(0).isRenamable()) {
1336       LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits,
1337                                         TRI);
1338       continue;
1339     }
1340 
1341     // Don't sink the COPY if it would violate a register dependency.
1342     if (hasRegisterDependency(MI, UsedOpsInCopy, DefedRegsInCopy,
1343                               ModifiedRegUnits, UsedRegUnits)) {
1344       LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits,
1345                                         TRI);
1346       continue;
1347     }
1348     assert((!UsedOpsInCopy.empty() && !DefedRegsInCopy.empty()) &&
1349            "Unexpect SrcReg or DefReg");
1350     MachineBasicBlock *SuccBB =
1351         getSingleLiveInSuccBB(CurBB, SinkableBBs, DefedRegsInCopy, TRI);
1352     // Don't sink if we cannot find a single sinkable successor in which Reg
1353     // is live-in.
1354     if (!SuccBB) {
1355       LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits,
1356                                         TRI);
1357       continue;
1358     }
1359     assert((SuccBB->pred_size() == 1 && *SuccBB->pred_begin() == &CurBB) &&
1360            "Unexpected predecessor");
1361 
1362     // Collect DBG_VALUEs that must sink with this copy. We've previously
1363     // recorded which reg units that DBG_VALUEs read, if this instruction
1364     // writes any of those units then the corresponding DBG_VALUEs must sink.
1365     SetVector<MachineInstr *> DbgValsToSinkSet;
1366     SmallVector<MachineInstr *, 4> DbgValsToSink;
1367     for (auto &MO : MI->operands()) {
1368       if (!MO.isReg() || !MO.isDef())
1369         continue;
1370 
1371       SmallSet<unsigned, 4> Units = getRegUnits(MO.getReg(), TRI);
1372       for (unsigned Reg : Units)
1373         for (auto *MI : SeenDbgInstrs.lookup(Reg))
1374           DbgValsToSinkSet.insert(MI);
1375     }
1376     DbgValsToSink.insert(DbgValsToSink.begin(), DbgValsToSinkSet.begin(),
1377                          DbgValsToSinkSet.end());
1378 
1379     // Clear the kill flag if SrcReg is killed between MI and the end of the
1380     // block.
1381     clearKillFlags(MI, CurBB, UsedOpsInCopy, UsedRegUnits, TRI);
1382     MachineBasicBlock::iterator InsertPos = SuccBB->getFirstNonPHI();
1383     performSink(*MI, *SuccBB, InsertPos, DbgValsToSink);
1384     updateLiveIn(MI, SuccBB, UsedOpsInCopy, DefedRegsInCopy);
1385 
1386     Changed = true;
1387     ++NumPostRACopySink;
1388   }
1389   return Changed;
1390 }
1391 
1392 bool PostRAMachineSinking::runOnMachineFunction(MachineFunction &MF) {
1393   if (skipFunction(MF.getFunction()))
1394     return false;
1395 
1396   bool Changed = false;
1397   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1398   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
1399 
1400   ModifiedRegUnits.init(*TRI);
1401   UsedRegUnits.init(*TRI);
1402   for (auto &BB : MF)
1403     Changed |= tryToSinkCopy(BB, MF, TRI, TII);
1404 
1405   return Changed;
1406 }
1407