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