xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/MachineSink.cpp (revision 04eeddc0aa8e0a417a16eaf9d7d095207f4a8623)
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/MapVector.h"
20 #include "llvm/ADT/PointerIntPair.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/SparseBitVector.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/CodeGen/MachineBasicBlock.h"
28 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
29 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
30 #include "llvm/CodeGen/MachineDominators.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineFunctionPass.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineLoopInfo.h"
35 #include "llvm/CodeGen/MachineOperand.h"
36 #include "llvm/CodeGen/MachinePostDominators.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/RegisterClassInfo.h"
39 #include "llvm/CodeGen/RegisterPressure.h"
40 #include "llvm/CodeGen/TargetInstrInfo.h"
41 #include "llvm/CodeGen/TargetRegisterInfo.h"
42 #include "llvm/CodeGen/TargetSubtargetInfo.h"
43 #include "llvm/IR/BasicBlock.h"
44 #include "llvm/IR/DebugInfoMetadata.h"
45 #include "llvm/IR/LLVMContext.h"
46 #include "llvm/InitializePasses.h"
47 #include "llvm/MC/MCRegisterInfo.h"
48 #include "llvm/Pass.h"
49 #include "llvm/Support/BranchProbability.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include <algorithm>
54 #include <cassert>
55 #include <cstdint>
56 #include <map>
57 #include <utility>
58 #include <vector>
59 
60 using namespace llvm;
61 
62 #define DEBUG_TYPE "machine-sink"
63 
64 static cl::opt<bool>
65 SplitEdges("machine-sink-split",
66            cl::desc("Split critical edges during machine sinking"),
67            cl::init(true), cl::Hidden);
68 
69 static cl::opt<bool>
70 UseBlockFreqInfo("machine-sink-bfi",
71            cl::desc("Use block frequency info to find successors to sink"),
72            cl::init(true), cl::Hidden);
73 
74 static cl::opt<unsigned> SplitEdgeProbabilityThreshold(
75     "machine-sink-split-probability-threshold",
76     cl::desc(
77         "Percentage threshold for splitting single-instruction critical edge. "
78         "If the branch threshold is higher than this threshold, we allow "
79         "speculative execution of up to 1 instruction to avoid branching to "
80         "splitted critical edge"),
81     cl::init(40), cl::Hidden);
82 
83 static cl::opt<unsigned> SinkLoadInstsPerBlockThreshold(
84     "machine-sink-load-instrs-threshold",
85     cl::desc("Do not try to find alias store for a load if there is a in-path "
86              "block whose instruction number is higher than this threshold."),
87     cl::init(2000), cl::Hidden);
88 
89 static cl::opt<unsigned> SinkLoadBlocksThreshold(
90     "machine-sink-load-blocks-threshold",
91     cl::desc("Do not try to find alias store for a load if the block number in "
92              "the straight line is higher than this threshold."),
93     cl::init(20), cl::Hidden);
94 
95 static cl::opt<bool>
96 SinkInstsIntoLoop("sink-insts-to-avoid-spills",
97                   cl::desc("Sink instructions into loops to avoid "
98                            "register spills"),
99                   cl::init(false), cl::Hidden);
100 
101 static cl::opt<unsigned> SinkIntoLoopLimit(
102     "machine-sink-loop-limit",
103     cl::desc("The maximum number of instructions considered for loop sinking."),
104     cl::init(50), cl::Hidden);
105 
106 STATISTIC(NumSunk,      "Number of machine instructions sunk");
107 STATISTIC(NumLoopSunk,  "Number of machine instructions sunk into a loop");
108 STATISTIC(NumSplit,     "Number of critical edges split");
109 STATISTIC(NumCoalesces, "Number of copies coalesced");
110 STATISTIC(NumPostRACopySink, "Number of copies sunk after RA");
111 
112 namespace {
113 
114   class MachineSinking : public MachineFunctionPass {
115     const TargetInstrInfo *TII;
116     const TargetRegisterInfo *TRI;
117     MachineRegisterInfo  *MRI;     // Machine register information
118     MachineDominatorTree *DT;      // Machine dominator tree
119     MachinePostDominatorTree *PDT; // Machine post dominator tree
120     MachineLoopInfo *LI;
121     MachineBlockFrequencyInfo *MBFI;
122     const MachineBranchProbabilityInfo *MBPI;
123     AliasAnalysis *AA;
124     RegisterClassInfo RegClassInfo;
125 
126     // Remember which edges have been considered for breaking.
127     SmallSet<std::pair<MachineBasicBlock*, MachineBasicBlock*>, 8>
128     CEBCandidates;
129     // Remember which edges we are about to split.
130     // This is different from CEBCandidates since those edges
131     // will be split.
132     SetVector<std::pair<MachineBasicBlock *, MachineBasicBlock *>> ToSplit;
133 
134     DenseSet<Register> RegsToClearKillFlags;
135 
136     using AllSuccsCache =
137         std::map<MachineBasicBlock *, SmallVector<MachineBasicBlock *, 4>>;
138 
139     /// DBG_VALUE pointer and flag. The flag is true if this DBG_VALUE is
140     /// post-dominated by another DBG_VALUE of the same variable location.
141     /// This is necessary to detect sequences such as:
142     ///     %0 = someinst
143     ///     DBG_VALUE %0, !123, !DIExpression()
144     ///     %1 = anotherinst
145     ///     DBG_VALUE %1, !123, !DIExpression()
146     /// Where if %0 were to sink, the DBG_VAUE should not sink with it, as that
147     /// would re-order assignments.
148     using SeenDbgUser = PointerIntPair<MachineInstr *, 1>;
149 
150     /// Record of DBG_VALUE uses of vregs in a block, so that we can identify
151     /// debug instructions to sink.
152     SmallDenseMap<unsigned, TinyPtrVector<SeenDbgUser>> SeenDbgUsers;
153 
154     /// Record of debug variables that have had their locations set in the
155     /// current block.
156     DenseSet<DebugVariable> SeenDbgVars;
157 
158     std::map<std::pair<MachineBasicBlock *, MachineBasicBlock *>, bool>
159         HasStoreCache;
160     std::map<std::pair<MachineBasicBlock *, MachineBasicBlock *>,
161              std::vector<MachineInstr *>>
162         StoreInstrCache;
163 
164     /// Cached BB's register pressure.
165     std::map<MachineBasicBlock *, std::vector<unsigned>> CachedRegisterPressure;
166 
167   public:
168     static char ID; // Pass identification
169 
170     MachineSinking() : MachineFunctionPass(ID) {
171       initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
172     }
173 
174     bool runOnMachineFunction(MachineFunction &MF) override;
175 
176     void getAnalysisUsage(AnalysisUsage &AU) const override {
177       MachineFunctionPass::getAnalysisUsage(AU);
178       AU.addRequired<AAResultsWrapperPass>();
179       AU.addRequired<MachineDominatorTree>();
180       AU.addRequired<MachinePostDominatorTree>();
181       AU.addRequired<MachineLoopInfo>();
182       AU.addRequired<MachineBranchProbabilityInfo>();
183       AU.addPreserved<MachineLoopInfo>();
184       if (UseBlockFreqInfo)
185         AU.addRequired<MachineBlockFrequencyInfo>();
186     }
187 
188     void releaseMemory() override {
189       CEBCandidates.clear();
190     }
191 
192   private:
193     bool ProcessBlock(MachineBasicBlock &MBB);
194     void ProcessDbgInst(MachineInstr &MI);
195     bool isWorthBreakingCriticalEdge(MachineInstr &MI,
196                                      MachineBasicBlock *From,
197                                      MachineBasicBlock *To);
198 
199     bool hasStoreBetween(MachineBasicBlock *From, MachineBasicBlock *To,
200                          MachineInstr &MI);
201 
202     /// Postpone the splitting of the given critical
203     /// edge (\p From, \p To).
204     ///
205     /// We do not split the edges on the fly. Indeed, this invalidates
206     /// the dominance information and thus triggers a lot of updates
207     /// of that information underneath.
208     /// Instead, we postpone all the splits after each iteration of
209     /// the main loop. That way, the information is at least valid
210     /// for the lifetime of an iteration.
211     ///
212     /// \return True if the edge is marked as toSplit, false otherwise.
213     /// False can be returned if, for instance, this is not profitable.
214     bool PostponeSplitCriticalEdge(MachineInstr &MI,
215                                    MachineBasicBlock *From,
216                                    MachineBasicBlock *To,
217                                    bool BreakPHIEdge);
218     bool SinkInstruction(MachineInstr &MI, bool &SawStore,
219                          AllSuccsCache &AllSuccessors);
220 
221     /// If we sink a COPY inst, some debug users of it's destination may no
222     /// longer be dominated by the COPY, and will eventually be dropped.
223     /// This is easily rectified by forwarding the non-dominated debug uses
224     /// to the copy source.
225     void SalvageUnsunkDebugUsersOfCopy(MachineInstr &,
226                                        MachineBasicBlock *TargetBlock);
227     bool AllUsesDominatedByBlock(Register Reg, MachineBasicBlock *MBB,
228                                  MachineBasicBlock *DefMBB, bool &BreakPHIEdge,
229                                  bool &LocalUse) const;
230     MachineBasicBlock *FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
231                bool &BreakPHIEdge, AllSuccsCache &AllSuccessors);
232 
233     void FindLoopSinkCandidates(MachineLoop *L, MachineBasicBlock *BB,
234                                 SmallVectorImpl<MachineInstr *> &Candidates);
235     bool SinkIntoLoop(MachineLoop *L, MachineInstr &I);
236 
237     bool isProfitableToSinkTo(Register Reg, MachineInstr &MI,
238                               MachineBasicBlock *MBB,
239                               MachineBasicBlock *SuccToSinkTo,
240                               AllSuccsCache &AllSuccessors);
241 
242     bool PerformTrivialForwardCoalescing(MachineInstr &MI,
243                                          MachineBasicBlock *MBB);
244 
245     SmallVector<MachineBasicBlock *, 4> &
246     GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
247                            AllSuccsCache &AllSuccessors) const;
248 
249     std::vector<unsigned> &getBBRegisterPressure(MachineBasicBlock &MBB);
250   };
251 
252 } // end anonymous namespace
253 
254 char MachineSinking::ID = 0;
255 
256 char &llvm::MachineSinkingID = MachineSinking::ID;
257 
258 INITIALIZE_PASS_BEGIN(MachineSinking, DEBUG_TYPE,
259                       "Machine code sinking", false, false)
260 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
261 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
262 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
263 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
264 INITIALIZE_PASS_END(MachineSinking, DEBUG_TYPE,
265                     "Machine code sinking", false, false)
266 
267 bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr &MI,
268                                                      MachineBasicBlock *MBB) {
269   if (!MI.isCopy())
270     return false;
271 
272   Register SrcReg = MI.getOperand(1).getReg();
273   Register DstReg = MI.getOperand(0).getReg();
274   if (!Register::isVirtualRegister(SrcReg) ||
275       !Register::isVirtualRegister(DstReg) || !MRI->hasOneNonDBGUse(SrcReg))
276     return false;
277 
278   const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
279   const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
280   if (SRC != DRC)
281     return false;
282 
283   MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
284   if (DefMI->isCopyLike())
285     return false;
286   LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI);
287   LLVM_DEBUG(dbgs() << "*** to: " << MI);
288   MRI->replaceRegWith(DstReg, SrcReg);
289   MI.eraseFromParent();
290 
291   // Conservatively, clear any kill flags, since it's possible that they are no
292   // longer correct.
293   MRI->clearKillFlags(SrcReg);
294 
295   ++NumCoalesces;
296   return true;
297 }
298 
299 /// AllUsesDominatedByBlock - Return true if all uses of the specified register
300 /// occur in blocks dominated by the specified block. If any use is in the
301 /// definition block, then return false since it is never legal to move def
302 /// after uses.
303 bool MachineSinking::AllUsesDominatedByBlock(Register Reg,
304                                              MachineBasicBlock *MBB,
305                                              MachineBasicBlock *DefMBB,
306                                              bool &BreakPHIEdge,
307                                              bool &LocalUse) const {
308   assert(Register::isVirtualRegister(Reg) && "Only makes sense for vregs");
309 
310   // Ignore debug uses because debug info doesn't affect the code.
311   if (MRI->use_nodbg_empty(Reg))
312     return true;
313 
314   // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
315   // into and they are all PHI nodes. In this case, machine-sink must break
316   // the critical edge first. e.g.
317   //
318   // %bb.1:
319   //   Predecessors according to CFG: %bb.0
320   //     ...
321   //     %def = DEC64_32r %x, implicit-def dead %eflags
322   //     ...
323   //     JE_4 <%bb.37>, implicit %eflags
324   //   Successors according to CFG: %bb.37 %bb.2
325   //
326   // %bb.2:
327   //     %p = PHI %y, %bb.0, %def, %bb.1
328   if (all_of(MRI->use_nodbg_operands(Reg), [&](MachineOperand &MO) {
329         MachineInstr *UseInst = MO.getParent();
330         unsigned OpNo = UseInst->getOperandNo(&MO);
331         MachineBasicBlock *UseBlock = UseInst->getParent();
332         return UseBlock == MBB && UseInst->isPHI() &&
333                UseInst->getOperand(OpNo + 1).getMBB() == DefMBB;
334       })) {
335     BreakPHIEdge = true;
336     return true;
337   }
338 
339   for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
340     // Determine the block of the use.
341     MachineInstr *UseInst = MO.getParent();
342     unsigned OpNo = &MO - &UseInst->getOperand(0);
343     MachineBasicBlock *UseBlock = UseInst->getParent();
344     if (UseInst->isPHI()) {
345       // PHI nodes use the operand in the predecessor block, not the block with
346       // the PHI.
347       UseBlock = UseInst->getOperand(OpNo+1).getMBB();
348     } else if (UseBlock == DefMBB) {
349       LocalUse = true;
350       return false;
351     }
352 
353     // Check that it dominates.
354     if (!DT->dominates(MBB, UseBlock))
355       return false;
356   }
357 
358   return true;
359 }
360 
361 /// Return true if this machine instruction loads from global offset table or
362 /// constant pool.
363 static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
364   assert(MI.mayLoad() && "Expected MI that loads!");
365 
366   // If we lost memory operands, conservatively assume that the instruction
367   // reads from everything..
368   if (MI.memoperands_empty())
369     return true;
370 
371   for (MachineMemOperand *MemOp : MI.memoperands())
372     if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
373       if (PSV->isGOT() || PSV->isConstantPool())
374         return true;
375 
376   return false;
377 }
378 
379 void MachineSinking::FindLoopSinkCandidates(MachineLoop *L, MachineBasicBlock *BB,
380     SmallVectorImpl<MachineInstr *> &Candidates) {
381   for (auto &MI : *BB) {
382     LLVM_DEBUG(dbgs() << "LoopSink: Analysing candidate: " << MI);
383     if (!TII->shouldSink(MI)) {
384       LLVM_DEBUG(dbgs() << "LoopSink: Instruction not a candidate for this "
385                            "target\n");
386       continue;
387     }
388     if (!L->isLoopInvariant(MI)) {
389       LLVM_DEBUG(dbgs() << "LoopSink: Instruction is not loop invariant\n");
390       continue;
391     }
392     bool DontMoveAcrossStore = true;
393     if (!MI.isSafeToMove(AA, DontMoveAcrossStore)) {
394       LLVM_DEBUG(dbgs() << "LoopSink: Instruction not safe to move.\n");
395       continue;
396     }
397     if (MI.mayLoad() && !mayLoadFromGOTOrConstantPool(MI)) {
398       LLVM_DEBUG(dbgs() << "LoopSink: Dont sink GOT or constant pool loads\n");
399       continue;
400     }
401     if (MI.isConvergent())
402       continue;
403 
404     const MachineOperand &MO = MI.getOperand(0);
405     if (!MO.isReg() || !MO.getReg() || !MO.isDef())
406       continue;
407     if (!MRI->hasOneDef(MO.getReg()))
408       continue;
409 
410     LLVM_DEBUG(dbgs() << "LoopSink: Instruction added as candidate.\n");
411     Candidates.push_back(&MI);
412   }
413 }
414 
415 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
416   if (skipFunction(MF.getFunction()))
417     return false;
418 
419   LLVM_DEBUG(dbgs() << "******** Machine Sinking ********\n");
420 
421   TII = MF.getSubtarget().getInstrInfo();
422   TRI = MF.getSubtarget().getRegisterInfo();
423   MRI = &MF.getRegInfo();
424   DT = &getAnalysis<MachineDominatorTree>();
425   PDT = &getAnalysis<MachinePostDominatorTree>();
426   LI = &getAnalysis<MachineLoopInfo>();
427   MBFI = UseBlockFreqInfo ? &getAnalysis<MachineBlockFrequencyInfo>() : nullptr;
428   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
429   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
430   RegClassInfo.runOnMachineFunction(MF);
431 
432   bool EverMadeChange = false;
433 
434   while (true) {
435     bool MadeChange = false;
436 
437     // Process all basic blocks.
438     CEBCandidates.clear();
439     ToSplit.clear();
440     for (auto &MBB: MF)
441       MadeChange |= ProcessBlock(MBB);
442 
443     // If we have anything we marked as toSplit, split it now.
444     for (auto &Pair : ToSplit) {
445       auto NewSucc = Pair.first->SplitCriticalEdge(Pair.second, *this);
446       if (NewSucc != nullptr) {
447         LLVM_DEBUG(dbgs() << " *** Splitting critical edge: "
448                           << printMBBReference(*Pair.first) << " -- "
449                           << printMBBReference(*NewSucc) << " -- "
450                           << printMBBReference(*Pair.second) << '\n');
451         if (MBFI)
452           MBFI->onEdgeSplit(*Pair.first, *NewSucc, *MBPI);
453 
454         MadeChange = true;
455         ++NumSplit;
456       } else
457         LLVM_DEBUG(dbgs() << " *** Not legal to break critical edge\n");
458     }
459     // If this iteration over the code changed anything, keep iterating.
460     if (!MadeChange) break;
461     EverMadeChange = true;
462   }
463 
464   if (SinkInstsIntoLoop) {
465     SmallVector<MachineLoop *, 8> Loops(LI->begin(), LI->end());
466     for (auto *L : Loops) {
467       MachineBasicBlock *Preheader = LI->findLoopPreheader(L);
468       if (!Preheader) {
469         LLVM_DEBUG(dbgs() << "LoopSink: Can't find preheader\n");
470         continue;
471       }
472       SmallVector<MachineInstr *, 8> Candidates;
473       FindLoopSinkCandidates(L, Preheader, Candidates);
474 
475       // Walk the candidates in reverse order so that we start with the use
476       // of a def-use chain, if there is any.
477       // TODO: Sort the candidates using a cost-model.
478       unsigned i = 0;
479       for (MachineInstr *I : llvm::reverse(Candidates)) {
480         if (i++ == SinkIntoLoopLimit) {
481           LLVM_DEBUG(dbgs() << "LoopSink:   Limit reached of instructions to "
482                                "be analysed.");
483           break;
484         }
485 
486         if (!SinkIntoLoop(L, *I))
487           break;
488         EverMadeChange = true;
489         ++NumLoopSunk;
490       }
491     }
492   }
493 
494   HasStoreCache.clear();
495   StoreInstrCache.clear();
496 
497   // Now clear any kill flags for recorded registers.
498   for (auto I : RegsToClearKillFlags)
499     MRI->clearKillFlags(I);
500   RegsToClearKillFlags.clear();
501 
502   return EverMadeChange;
503 }
504 
505 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
506   // Can't sink anything out of a block that has less than two successors.
507   if (MBB.succ_size() <= 1 || MBB.empty()) return false;
508 
509   // Don't bother sinking code out of unreachable blocks. In addition to being
510   // unprofitable, it can also lead to infinite looping, because in an
511   // unreachable loop there may be nowhere to stop.
512   if (!DT->isReachableFromEntry(&MBB)) return false;
513 
514   bool MadeChange = false;
515 
516   // Cache all successors, sorted by frequency info and loop depth.
517   AllSuccsCache AllSuccessors;
518 
519   // Walk the basic block bottom-up.  Remember if we saw a store.
520   MachineBasicBlock::iterator I = MBB.end();
521   --I;
522   bool ProcessedBegin, SawStore = false;
523   do {
524     MachineInstr &MI = *I;  // The instruction to sink.
525 
526     // Predecrement I (if it's not begin) so that it isn't invalidated by
527     // sinking.
528     ProcessedBegin = I == MBB.begin();
529     if (!ProcessedBegin)
530       --I;
531 
532     if (MI.isDebugOrPseudoInstr()) {
533       if (MI.isDebugValue())
534         ProcessDbgInst(MI);
535       continue;
536     }
537 
538     bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
539     if (Joined) {
540       MadeChange = true;
541       continue;
542     }
543 
544     if (SinkInstruction(MI, SawStore, AllSuccessors)) {
545       ++NumSunk;
546       MadeChange = true;
547     }
548 
549     // If we just processed the first instruction in the block, we're done.
550   } while (!ProcessedBegin);
551 
552   SeenDbgUsers.clear();
553   SeenDbgVars.clear();
554   // recalculate the bb register pressure after sinking one BB.
555   CachedRegisterPressure.clear();
556 
557   return MadeChange;
558 }
559 
560 void MachineSinking::ProcessDbgInst(MachineInstr &MI) {
561   // When we see DBG_VALUEs for registers, record any vreg it reads, so that
562   // we know what to sink if the vreg def sinks.
563   assert(MI.isDebugValue() && "Expected DBG_VALUE for processing");
564 
565   DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
566                     MI.getDebugLoc()->getInlinedAt());
567   bool SeenBefore = SeenDbgVars.contains(Var);
568 
569   for (MachineOperand &MO : MI.debug_operands()) {
570     if (MO.isReg() && MO.getReg().isVirtual())
571       SeenDbgUsers[MO.getReg()].push_back(SeenDbgUser(&MI, SeenBefore));
572   }
573 
574   // Record the variable for any DBG_VALUE, to avoid re-ordering any of them.
575   SeenDbgVars.insert(Var);
576 }
577 
578 bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr &MI,
579                                                  MachineBasicBlock *From,
580                                                  MachineBasicBlock *To) {
581   // FIXME: Need much better heuristics.
582 
583   // If the pass has already considered breaking this edge (during this pass
584   // through the function), then let's go ahead and break it. This means
585   // sinking multiple "cheap" instructions into the same block.
586   if (!CEBCandidates.insert(std::make_pair(From, To)).second)
587     return true;
588 
589   if (!MI.isCopy() && !TII->isAsCheapAsAMove(MI))
590     return true;
591 
592   if (From->isSuccessor(To) && MBPI->getEdgeProbability(From, To) <=
593       BranchProbability(SplitEdgeProbabilityThreshold, 100))
594     return true;
595 
596   // MI is cheap, we probably don't want to break the critical edge for it.
597   // However, if this would allow some definitions of its source operands
598   // to be sunk then it's probably worth it.
599   for (const MachineOperand &MO : MI.operands()) {
600     if (!MO.isReg() || !MO.isUse())
601       continue;
602     Register Reg = MO.getReg();
603     if (Reg == 0)
604       continue;
605 
606     // We don't move live definitions of physical registers,
607     // so sinking their uses won't enable any opportunities.
608     if (Register::isPhysicalRegister(Reg))
609       continue;
610 
611     // If this instruction is the only user of a virtual register,
612     // check if breaking the edge will enable sinking
613     // both this instruction and the defining instruction.
614     if (MRI->hasOneNonDBGUse(Reg)) {
615       // If the definition resides in same MBB,
616       // claim it's likely we can sink these together.
617       // If definition resides elsewhere, we aren't
618       // blocking it from being sunk so don't break the edge.
619       MachineInstr *DefMI = MRI->getVRegDef(Reg);
620       if (DefMI->getParent() == MI.getParent())
621         return true;
622     }
623   }
624 
625   return false;
626 }
627 
628 bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr &MI,
629                                                MachineBasicBlock *FromBB,
630                                                MachineBasicBlock *ToBB,
631                                                bool BreakPHIEdge) {
632   if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
633     return false;
634 
635   // Avoid breaking back edge. From == To means backedge for single BB loop.
636   if (!SplitEdges || FromBB == ToBB)
637     return false;
638 
639   // Check for backedges of more "complex" loops.
640   if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
641       LI->isLoopHeader(ToBB))
642     return false;
643 
644   // It's not always legal to break critical edges and sink the computation
645   // to the edge.
646   //
647   // %bb.1:
648   // v1024
649   // Beq %bb.3
650   // <fallthrough>
651   // %bb.2:
652   // ... no uses of v1024
653   // <fallthrough>
654   // %bb.3:
655   // ...
656   //       = v1024
657   //
658   // If %bb.1 -> %bb.3 edge is broken and computation of v1024 is inserted:
659   //
660   // %bb.1:
661   // ...
662   // Bne %bb.2
663   // %bb.4:
664   // v1024 =
665   // B %bb.3
666   // %bb.2:
667   // ... no uses of v1024
668   // <fallthrough>
669   // %bb.3:
670   // ...
671   //       = v1024
672   //
673   // This is incorrect since v1024 is not computed along the %bb.1->%bb.2->%bb.3
674   // flow. We need to ensure the new basic block where the computation is
675   // sunk to dominates all the uses.
676   // It's only legal to break critical edge and sink the computation to the
677   // new block if all the predecessors of "To", except for "From", are
678   // not dominated by "From". Given SSA property, this means these
679   // predecessors are dominated by "To".
680   //
681   // There is no need to do this check if all the uses are PHI nodes. PHI
682   // sources are only defined on the specific predecessor edges.
683   if (!BreakPHIEdge) {
684     for (MachineBasicBlock *Pred : ToBB->predecessors())
685       if (Pred != FromBB && !DT->dominates(ToBB, Pred))
686         return false;
687   }
688 
689   ToSplit.insert(std::make_pair(FromBB, ToBB));
690 
691   return true;
692 }
693 
694 std::vector<unsigned> &
695 MachineSinking::getBBRegisterPressure(MachineBasicBlock &MBB) {
696   // Currently to save compiling time, MBB's register pressure will not change
697   // in one ProcessBlock iteration because of CachedRegisterPressure. but MBB's
698   // register pressure is changed after sinking any instructions into it.
699   // FIXME: need a accurate and cheap register pressure estiminate model here.
700   auto RP = CachedRegisterPressure.find(&MBB);
701   if (RP != CachedRegisterPressure.end())
702     return RP->second;
703 
704   RegionPressure Pressure;
705   RegPressureTracker RPTracker(Pressure);
706 
707   // Initialize the register pressure tracker.
708   RPTracker.init(MBB.getParent(), &RegClassInfo, nullptr, &MBB, MBB.end(),
709                  /*TrackLaneMasks*/ false, /*TrackUntiedDefs=*/true);
710 
711   for (MachineBasicBlock::iterator MII = MBB.instr_end(),
712                                    MIE = MBB.instr_begin();
713        MII != MIE; --MII) {
714     MachineInstr &MI = *std::prev(MII);
715     if (MI.isDebugInstr() || MI.isPseudoProbe())
716       continue;
717     RegisterOperands RegOpers;
718     RegOpers.collect(MI, *TRI, *MRI, false, false);
719     RPTracker.recedeSkipDebugValues();
720     assert(&*RPTracker.getPos() == &MI && "RPTracker sync error!");
721     RPTracker.recede(RegOpers);
722   }
723 
724   RPTracker.closeRegion();
725   auto It = CachedRegisterPressure.insert(
726       std::make_pair(&MBB, RPTracker.getPressure().MaxSetPressure));
727   return It.first->second;
728 }
729 
730 /// isProfitableToSinkTo - Return true if it is profitable to sink MI.
731 bool MachineSinking::isProfitableToSinkTo(Register Reg, MachineInstr &MI,
732                                           MachineBasicBlock *MBB,
733                                           MachineBasicBlock *SuccToSinkTo,
734                                           AllSuccsCache &AllSuccessors) {
735   assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
736 
737   if (MBB == SuccToSinkTo)
738     return false;
739 
740   // It is profitable if SuccToSinkTo does not post dominate current block.
741   if (!PDT->dominates(SuccToSinkTo, MBB))
742     return true;
743 
744   // It is profitable to sink an instruction from a deeper loop to a shallower
745   // loop, even if the latter post-dominates the former (PR21115).
746   if (LI->getLoopDepth(MBB) > LI->getLoopDepth(SuccToSinkTo))
747     return true;
748 
749   // Check if only use in post dominated block is PHI instruction.
750   bool NonPHIUse = false;
751   for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) {
752     MachineBasicBlock *UseBlock = UseInst.getParent();
753     if (UseBlock == SuccToSinkTo && !UseInst.isPHI())
754       NonPHIUse = true;
755   }
756   if (!NonPHIUse)
757     return true;
758 
759   // If SuccToSinkTo post dominates then also it may be profitable if MI
760   // can further profitably sinked into another block in next round.
761   bool BreakPHIEdge = false;
762   // FIXME - If finding successor is compile time expensive then cache results.
763   if (MachineBasicBlock *MBB2 =
764           FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge, AllSuccessors))
765     return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2, AllSuccessors);
766 
767   MachineLoop *ML = LI->getLoopFor(MBB);
768 
769   // If the instruction is not inside a loop, it is not profitable to sink MI to
770   // a post dominate block SuccToSinkTo.
771   if (!ML)
772     return false;
773 
774   auto isRegisterPressureSetExceedLimit = [&](const TargetRegisterClass *RC) {
775     unsigned Weight = TRI->getRegClassWeight(RC).RegWeight;
776     const int *PS = TRI->getRegClassPressureSets(RC);
777     // Get register pressure for block SuccToSinkTo.
778     std::vector<unsigned> BBRegisterPressure =
779         getBBRegisterPressure(*SuccToSinkTo);
780     for (; *PS != -1; PS++)
781       // check if any register pressure set exceeds limit in block SuccToSinkTo
782       // after sinking.
783       if (Weight + BBRegisterPressure[*PS] >=
784           TRI->getRegPressureSetLimit(*MBB->getParent(), *PS))
785         return true;
786     return false;
787   };
788 
789   // If this instruction is inside a loop and sinking this instruction can make
790   // more registers live range shorten, it is still prifitable.
791   for (const MachineOperand &MO : MI.operands()) {
792     // Ignore non-register operands.
793     if (!MO.isReg())
794       continue;
795     Register Reg = MO.getReg();
796     if (Reg == 0)
797       continue;
798 
799     if (Register::isPhysicalRegister(Reg)) {
800       if (MO.isUse() &&
801           (MRI->isConstantPhysReg(Reg) || TII->isIgnorableUse(MO)))
802         continue;
803 
804       // Don't handle non-constant and non-ignorable physical register.
805       return false;
806     }
807 
808     // Users for the defs are all dominated by SuccToSinkTo.
809     if (MO.isDef()) {
810       // This def register's live range is shortened after sinking.
811       bool LocalUse = false;
812       if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB, BreakPHIEdge,
813                                    LocalUse))
814         return false;
815     } else {
816       MachineInstr *DefMI = MRI->getVRegDef(Reg);
817       // DefMI is defined outside of loop. There should be no live range
818       // impact for this operand. Defination outside of loop means:
819       // 1: defination is outside of loop.
820       // 2: defination is in this loop, but it is a PHI in the loop header.
821       if (LI->getLoopFor(DefMI->getParent()) != ML ||
822           (DefMI->isPHI() && LI->isLoopHeader(DefMI->getParent())))
823         continue;
824       // The DefMI is defined inside the loop.
825       // If sinking this operand makes some register pressure set exceed limit,
826       // it is not profitable.
827       if (isRegisterPressureSetExceedLimit(MRI->getRegClass(Reg))) {
828         LLVM_DEBUG(dbgs() << "register pressure exceed limit, not profitable.");
829         return false;
830       }
831     }
832   }
833 
834   // If MI is in loop and all its operands are alive across the whole loop or if
835   // no operand sinking make register pressure set exceed limit, it is
836   // profitable to sink MI.
837   return true;
838 }
839 
840 /// Get the sorted sequence of successors for this MachineBasicBlock, possibly
841 /// computing it if it was not already cached.
842 SmallVector<MachineBasicBlock *, 4> &
843 MachineSinking::GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
844                                        AllSuccsCache &AllSuccessors) const {
845   // Do we have the sorted successors in cache ?
846   auto Succs = AllSuccessors.find(MBB);
847   if (Succs != AllSuccessors.end())
848     return Succs->second;
849 
850   SmallVector<MachineBasicBlock *, 4> AllSuccs(MBB->successors());
851 
852   // Handle cases where sinking can happen but where the sink point isn't a
853   // successor. For example:
854   //
855   //   x = computation
856   //   if () {} else {}
857   //   use x
858   //
859   for (MachineDomTreeNode *DTChild : DT->getNode(MBB)->children()) {
860     // DomTree children of MBB that have MBB as immediate dominator are added.
861     if (DTChild->getIDom()->getBlock() == MI.getParent() &&
862         // Skip MBBs already added to the AllSuccs vector above.
863         !MBB->isSuccessor(DTChild->getBlock()))
864       AllSuccs.push_back(DTChild->getBlock());
865   }
866 
867   // Sort Successors according to their loop depth or block frequency info.
868   llvm::stable_sort(
869       AllSuccs, [this](const MachineBasicBlock *L, const MachineBasicBlock *R) {
870         uint64_t LHSFreq = MBFI ? MBFI->getBlockFreq(L).getFrequency() : 0;
871         uint64_t RHSFreq = MBFI ? MBFI->getBlockFreq(R).getFrequency() : 0;
872         bool HasBlockFreq = LHSFreq != 0 && RHSFreq != 0;
873         return HasBlockFreq ? LHSFreq < RHSFreq
874                             : LI->getLoopDepth(L) < LI->getLoopDepth(R);
875       });
876 
877   auto it = AllSuccessors.insert(std::make_pair(MBB, AllSuccs));
878 
879   return it.first->second;
880 }
881 
882 /// FindSuccToSinkTo - Find a successor to sink this instruction to.
883 MachineBasicBlock *
884 MachineSinking::FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
885                                  bool &BreakPHIEdge,
886                                  AllSuccsCache &AllSuccessors) {
887   assert (MBB && "Invalid MachineBasicBlock!");
888 
889   // Loop over all the operands of the specified instruction.  If there is
890   // anything we can't handle, bail out.
891 
892   // SuccToSinkTo - This is the successor to sink this instruction to, once we
893   // decide.
894   MachineBasicBlock *SuccToSinkTo = nullptr;
895   for (const MachineOperand &MO : MI.operands()) {
896     if (!MO.isReg()) continue;  // Ignore non-register operands.
897 
898     Register Reg = MO.getReg();
899     if (Reg == 0) continue;
900 
901     if (Register::isPhysicalRegister(Reg)) {
902       if (MO.isUse()) {
903         // If the physreg has no defs anywhere, it's just an ambient register
904         // and we can freely move its uses. Alternatively, if it's allocatable,
905         // it could get allocated to something with a def during allocation.
906         if (!MRI->isConstantPhysReg(Reg) && !TII->isIgnorableUse(MO))
907           return nullptr;
908       } else if (!MO.isDead()) {
909         // A def that isn't dead. We can't move it.
910         return nullptr;
911       }
912     } else {
913       // Virtual register uses are always safe to sink.
914       if (MO.isUse()) continue;
915 
916       // If it's not safe to move defs of the register class, then abort.
917       if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
918         return nullptr;
919 
920       // Virtual register defs can only be sunk if all their uses are in blocks
921       // dominated by one of the successors.
922       if (SuccToSinkTo) {
923         // If a previous operand picked a block to sink to, then this operand
924         // must be sinkable to the same block.
925         bool LocalUse = false;
926         if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
927                                      BreakPHIEdge, LocalUse))
928           return nullptr;
929 
930         continue;
931       }
932 
933       // Otherwise, we should look at all the successors and decide which one
934       // we should sink to. If we have reliable block frequency information
935       // (frequency != 0) available, give successors with smaller frequencies
936       // higher priority, otherwise prioritize smaller loop depths.
937       for (MachineBasicBlock *SuccBlock :
938            GetAllSortedSuccessors(MI, MBB, AllSuccessors)) {
939         bool LocalUse = false;
940         if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
941                                     BreakPHIEdge, LocalUse)) {
942           SuccToSinkTo = SuccBlock;
943           break;
944         }
945         if (LocalUse)
946           // Def is used locally, it's never safe to move this def.
947           return nullptr;
948       }
949 
950       // If we couldn't find a block to sink to, ignore this instruction.
951       if (!SuccToSinkTo)
952         return nullptr;
953       if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo, AllSuccessors))
954         return nullptr;
955     }
956   }
957 
958   // It is not possible to sink an instruction into its own block.  This can
959   // happen with loops.
960   if (MBB == SuccToSinkTo)
961     return nullptr;
962 
963   // It's not safe to sink instructions to EH landing pad. Control flow into
964   // landing pad is implicitly defined.
965   if (SuccToSinkTo && SuccToSinkTo->isEHPad())
966     return nullptr;
967 
968   // It ought to be okay to sink instructions into an INLINEASM_BR target, but
969   // only if we make sure that MI occurs _before_ an INLINEASM_BR instruction in
970   // the source block (which this code does not yet do). So for now, forbid
971   // doing so.
972   if (SuccToSinkTo && SuccToSinkTo->isInlineAsmBrIndirectTarget())
973     return nullptr;
974 
975   return SuccToSinkTo;
976 }
977 
978 /// Return true if MI is likely to be usable as a memory operation by the
979 /// implicit null check optimization.
980 ///
981 /// This is a "best effort" heuristic, and should not be relied upon for
982 /// correctness.  This returning true does not guarantee that the implicit null
983 /// check optimization is legal over MI, and this returning false does not
984 /// guarantee MI cannot possibly be used to do a null check.
985 static bool SinkingPreventsImplicitNullCheck(MachineInstr &MI,
986                                              const TargetInstrInfo *TII,
987                                              const TargetRegisterInfo *TRI) {
988   using MachineBranchPredicate = TargetInstrInfo::MachineBranchPredicate;
989 
990   auto *MBB = MI.getParent();
991   if (MBB->pred_size() != 1)
992     return false;
993 
994   auto *PredMBB = *MBB->pred_begin();
995   auto *PredBB = PredMBB->getBasicBlock();
996 
997   // Frontends that don't use implicit null checks have no reason to emit
998   // branches with make.implicit metadata, and this function should always
999   // return false for them.
1000   if (!PredBB ||
1001       !PredBB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit))
1002     return false;
1003 
1004   const MachineOperand *BaseOp;
1005   int64_t Offset;
1006   bool OffsetIsScalable;
1007   if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI))
1008     return false;
1009 
1010   if (!BaseOp->isReg())
1011     return false;
1012 
1013   if (!(MI.mayLoad() && !MI.isPredicable()))
1014     return false;
1015 
1016   MachineBranchPredicate MBP;
1017   if (TII->analyzeBranchPredicate(*PredMBB, MBP, false))
1018     return false;
1019 
1020   return MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
1021          (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
1022           MBP.Predicate == MachineBranchPredicate::PRED_EQ) &&
1023          MBP.LHS.getReg() == BaseOp->getReg();
1024 }
1025 
1026 /// If the sunk instruction is a copy, try to forward the copy instead of
1027 /// leaving an 'undef' DBG_VALUE in the original location. Don't do this if
1028 /// there's any subregister weirdness involved. Returns true if copy
1029 /// propagation occurred.
1030 static bool attemptDebugCopyProp(MachineInstr &SinkInst, MachineInstr &DbgMI,
1031                                  Register Reg) {
1032   const MachineRegisterInfo &MRI = SinkInst.getMF()->getRegInfo();
1033   const TargetInstrInfo &TII = *SinkInst.getMF()->getSubtarget().getInstrInfo();
1034 
1035   // Copy DBG_VALUE operand and set the original to undef. We then check to
1036   // see whether this is something that can be copy-forwarded. If it isn't,
1037   // continue around the loop.
1038 
1039   const MachineOperand *SrcMO = nullptr, *DstMO = nullptr;
1040   auto CopyOperands = TII.isCopyInstr(SinkInst);
1041   if (!CopyOperands)
1042     return false;
1043   SrcMO = CopyOperands->Source;
1044   DstMO = CopyOperands->Destination;
1045 
1046   // Check validity of forwarding this copy.
1047   bool PostRA = MRI.getNumVirtRegs() == 0;
1048 
1049   // Trying to forward between physical and virtual registers is too hard.
1050   if (Reg.isVirtual() != SrcMO->getReg().isVirtual())
1051     return false;
1052 
1053   // Only try virtual register copy-forwarding before regalloc, and physical
1054   // register copy-forwarding after regalloc.
1055   bool arePhysRegs = !Reg.isVirtual();
1056   if (arePhysRegs != PostRA)
1057     return false;
1058 
1059   // Pre-regalloc, only forward if all subregisters agree (or there are no
1060   // subregs at all). More analysis might recover some forwardable copies.
1061   if (!PostRA)
1062     for (auto &DbgMO : DbgMI.getDebugOperandsForReg(Reg))
1063       if (DbgMO.getSubReg() != SrcMO->getSubReg() ||
1064           DbgMO.getSubReg() != DstMO->getSubReg())
1065         return false;
1066 
1067   // Post-regalloc, we may be sinking a DBG_VALUE of a sub or super-register
1068   // of this copy. Only forward the copy if the DBG_VALUE operand exactly
1069   // matches the copy destination.
1070   if (PostRA && Reg != DstMO->getReg())
1071     return false;
1072 
1073   for (auto &DbgMO : DbgMI.getDebugOperandsForReg(Reg)) {
1074     DbgMO.setReg(SrcMO->getReg());
1075     DbgMO.setSubReg(SrcMO->getSubReg());
1076   }
1077   return true;
1078 }
1079 
1080 using MIRegs = std::pair<MachineInstr *, SmallVector<unsigned, 2>>;
1081 /// Sink an instruction and its associated debug instructions.
1082 static void performSink(MachineInstr &MI, MachineBasicBlock &SuccToSinkTo,
1083                         MachineBasicBlock::iterator InsertPos,
1084                         SmallVectorImpl<MIRegs> &DbgValuesToSink) {
1085 
1086   // If we cannot find a location to use (merge with), then we erase the debug
1087   // location to prevent debug-info driven tools from potentially reporting
1088   // wrong location information.
1089   if (!SuccToSinkTo.empty() && InsertPos != SuccToSinkTo.end())
1090     MI.setDebugLoc(DILocation::getMergedLocation(MI.getDebugLoc(),
1091                                                  InsertPos->getDebugLoc()));
1092   else
1093     MI.setDebugLoc(DebugLoc());
1094 
1095   // Move the instruction.
1096   MachineBasicBlock *ParentBlock = MI.getParent();
1097   SuccToSinkTo.splice(InsertPos, ParentBlock, MI,
1098                       ++MachineBasicBlock::iterator(MI));
1099 
1100   // Sink a copy of debug users to the insert position. Mark the original
1101   // DBG_VALUE location as 'undef', indicating that any earlier variable
1102   // location should be terminated as we've optimised away the value at this
1103   // point.
1104   for (auto DbgValueToSink : DbgValuesToSink) {
1105     MachineInstr *DbgMI = DbgValueToSink.first;
1106     MachineInstr *NewDbgMI = DbgMI->getMF()->CloneMachineInstr(DbgMI);
1107     SuccToSinkTo.insert(InsertPos, NewDbgMI);
1108 
1109     bool PropagatedAllSunkOps = true;
1110     for (unsigned Reg : DbgValueToSink.second) {
1111       if (DbgMI->hasDebugOperandForReg(Reg)) {
1112         if (!attemptDebugCopyProp(MI, *DbgMI, Reg)) {
1113           PropagatedAllSunkOps = false;
1114           break;
1115         }
1116       }
1117     }
1118     if (!PropagatedAllSunkOps)
1119       DbgMI->setDebugValueUndef();
1120   }
1121 }
1122 
1123 /// hasStoreBetween - check if there is store betweeen straight line blocks From
1124 /// and To.
1125 bool MachineSinking::hasStoreBetween(MachineBasicBlock *From,
1126                                      MachineBasicBlock *To, MachineInstr &MI) {
1127   // Make sure From and To are in straight line which means From dominates To
1128   // and To post dominates From.
1129   if (!DT->dominates(From, To) || !PDT->dominates(To, From))
1130     return true;
1131 
1132   auto BlockPair = std::make_pair(From, To);
1133 
1134   // Does these two blocks pair be queried before and have a definite cached
1135   // result?
1136   if (HasStoreCache.find(BlockPair) != HasStoreCache.end())
1137     return HasStoreCache[BlockPair];
1138 
1139   if (StoreInstrCache.find(BlockPair) != StoreInstrCache.end())
1140     return llvm::any_of(StoreInstrCache[BlockPair], [&](MachineInstr *I) {
1141       return I->mayAlias(AA, MI, false);
1142     });
1143 
1144   bool SawStore = false;
1145   bool HasAliasedStore = false;
1146   DenseSet<MachineBasicBlock *> HandledBlocks;
1147   DenseSet<MachineBasicBlock *> HandledDomBlocks;
1148   // Go through all reachable blocks from From.
1149   for (MachineBasicBlock *BB : depth_first(From)) {
1150     // We insert the instruction at the start of block To, so no need to worry
1151     // about stores inside To.
1152     // Store in block From should be already considered when just enter function
1153     // SinkInstruction.
1154     if (BB == To || BB == From)
1155       continue;
1156 
1157     // We already handle this BB in previous iteration.
1158     if (HandledBlocks.count(BB))
1159       continue;
1160 
1161     HandledBlocks.insert(BB);
1162     // To post dominates BB, it must be a path from block From.
1163     if (PDT->dominates(To, BB)) {
1164       if (!HandledDomBlocks.count(BB))
1165         HandledDomBlocks.insert(BB);
1166 
1167       // If this BB is too big or the block number in straight line between From
1168       // and To is too big, stop searching to save compiling time.
1169       if (BB->size() > SinkLoadInstsPerBlockThreshold ||
1170           HandledDomBlocks.size() > SinkLoadBlocksThreshold) {
1171         for (auto *DomBB : HandledDomBlocks) {
1172           if (DomBB != BB && DT->dominates(DomBB, BB))
1173             HasStoreCache[std::make_pair(DomBB, To)] = true;
1174           else if(DomBB != BB && DT->dominates(BB, DomBB))
1175             HasStoreCache[std::make_pair(From, DomBB)] = true;
1176         }
1177         HasStoreCache[BlockPair] = true;
1178         return true;
1179       }
1180 
1181       for (MachineInstr &I : *BB) {
1182         // Treat as alias conservatively for a call or an ordered memory
1183         // operation.
1184         if (I.isCall() || I.hasOrderedMemoryRef()) {
1185           for (auto *DomBB : HandledDomBlocks) {
1186             if (DomBB != BB && DT->dominates(DomBB, BB))
1187               HasStoreCache[std::make_pair(DomBB, To)] = true;
1188             else if(DomBB != BB && DT->dominates(BB, DomBB))
1189               HasStoreCache[std::make_pair(From, DomBB)] = true;
1190           }
1191           HasStoreCache[BlockPair] = true;
1192           return true;
1193         }
1194 
1195         if (I.mayStore()) {
1196           SawStore = true;
1197           // We still have chance to sink MI if all stores between are not
1198           // aliased to MI.
1199           // Cache all store instructions, so that we don't need to go through
1200           // all From reachable blocks for next load instruction.
1201           if (I.mayAlias(AA, MI, false))
1202             HasAliasedStore = true;
1203           StoreInstrCache[BlockPair].push_back(&I);
1204         }
1205       }
1206     }
1207   }
1208   // If there is no store at all, cache the result.
1209   if (!SawStore)
1210     HasStoreCache[BlockPair] = false;
1211   return HasAliasedStore;
1212 }
1213 
1214 /// Sink instructions into loops if profitable. This especially tries to prevent
1215 /// register spills caused by register pressure if there is little to no
1216 /// overhead moving instructions into loops.
1217 bool MachineSinking::SinkIntoLoop(MachineLoop *L, MachineInstr &I) {
1218   LLVM_DEBUG(dbgs() << "LoopSink: Finding sink block for: " << I);
1219   MachineBasicBlock *Preheader = L->getLoopPreheader();
1220   assert(Preheader && "Loop sink needs a preheader block");
1221   MachineBasicBlock *SinkBlock = nullptr;
1222   bool CanSink = true;
1223   const MachineOperand &MO = I.getOperand(0);
1224 
1225   for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
1226     LLVM_DEBUG(dbgs() << "LoopSink:   Analysing use: " << MI);
1227     if (!L->contains(&MI)) {
1228       LLVM_DEBUG(dbgs() << "LoopSink:   Use not in loop, can't sink.\n");
1229       CanSink = false;
1230       break;
1231     }
1232 
1233     // FIXME: Come up with a proper cost model that estimates whether sinking
1234     // the instruction (and thus possibly executing it on every loop
1235     // iteration) is more expensive than a register.
1236     // For now assumes that copies are cheap and thus almost always worth it.
1237     if (!MI.isCopy()) {
1238       LLVM_DEBUG(dbgs() << "LoopSink:   Use is not a copy\n");
1239       CanSink = false;
1240       break;
1241     }
1242     if (!SinkBlock) {
1243       SinkBlock = MI.getParent();
1244       LLVM_DEBUG(dbgs() << "LoopSink:   Setting sink block to: "
1245                         << printMBBReference(*SinkBlock) << "\n");
1246       continue;
1247     }
1248     SinkBlock = DT->findNearestCommonDominator(SinkBlock, MI.getParent());
1249     if (!SinkBlock) {
1250       LLVM_DEBUG(dbgs() << "LoopSink:   Can't find nearest dominator\n");
1251       CanSink = false;
1252       break;
1253     }
1254     LLVM_DEBUG(dbgs() << "LoopSink:   Setting nearest common dom block: " <<
1255                printMBBReference(*SinkBlock) << "\n");
1256   }
1257 
1258   if (!CanSink) {
1259     LLVM_DEBUG(dbgs() << "LoopSink: Can't sink instruction.\n");
1260     return false;
1261   }
1262   if (!SinkBlock) {
1263     LLVM_DEBUG(dbgs() << "LoopSink: Not sinking, can't find sink block.\n");
1264     return false;
1265   }
1266   if (SinkBlock == Preheader) {
1267     LLVM_DEBUG(dbgs() << "LoopSink: Not sinking, sink block is the preheader\n");
1268     return false;
1269   }
1270   if (SinkBlock->size() > SinkLoadInstsPerBlockThreshold) {
1271     LLVM_DEBUG(dbgs() << "LoopSink: Not Sinking, block too large to analyse.\n");
1272     return false;
1273   }
1274 
1275   LLVM_DEBUG(dbgs() << "LoopSink: Sinking instruction!\n");
1276   SinkBlock->splice(SinkBlock->getFirstNonPHI(), Preheader, I);
1277 
1278   // The instruction is moved from its basic block, so do not retain the
1279   // debug information.
1280   assert(!I.isDebugInstr() && "Should not sink debug inst");
1281   I.setDebugLoc(DebugLoc());
1282   return true;
1283 }
1284 
1285 /// SinkInstruction - Determine whether it is safe to sink the specified machine
1286 /// instruction out of its current block into a successor.
1287 bool MachineSinking::SinkInstruction(MachineInstr &MI, bool &SawStore,
1288                                      AllSuccsCache &AllSuccessors) {
1289   // Don't sink instructions that the target prefers not to sink.
1290   if (!TII->shouldSink(MI))
1291     return false;
1292 
1293   // Check if it's safe to move the instruction.
1294   if (!MI.isSafeToMove(AA, SawStore))
1295     return false;
1296 
1297   // Convergent operations may not be made control-dependent on additional
1298   // values.
1299   if (MI.isConvergent())
1300     return false;
1301 
1302   // Don't break implicit null checks.  This is a performance heuristic, and not
1303   // required for correctness.
1304   if (SinkingPreventsImplicitNullCheck(MI, TII, TRI))
1305     return false;
1306 
1307   // FIXME: This should include support for sinking instructions within the
1308   // block they are currently in to shorten the live ranges.  We often get
1309   // instructions sunk into the top of a large block, but it would be better to
1310   // also sink them down before their first use in the block.  This xform has to
1311   // be careful not to *increase* register pressure though, e.g. sinking
1312   // "x = y + z" down if it kills y and z would increase the live ranges of y
1313   // and z and only shrink the live range of x.
1314 
1315   bool BreakPHIEdge = false;
1316   MachineBasicBlock *ParentBlock = MI.getParent();
1317   MachineBasicBlock *SuccToSinkTo =
1318       FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge, AllSuccessors);
1319 
1320   // If there are no outputs, it must have side-effects.
1321   if (!SuccToSinkTo)
1322     return false;
1323 
1324   // If the instruction to move defines a dead physical register which is live
1325   // when leaving the basic block, don't move it because it could turn into a
1326   // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
1327   for (const MachineOperand &MO : MI.operands()) {
1328     if (!MO.isReg() || MO.isUse())
1329       continue;
1330     Register Reg = MO.getReg();
1331     if (Reg == 0 || !Register::isPhysicalRegister(Reg))
1332       continue;
1333     if (SuccToSinkTo->isLiveIn(Reg))
1334       return false;
1335   }
1336 
1337   LLVM_DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccToSinkTo);
1338 
1339   // If the block has multiple predecessors, this is a critical edge.
1340   // Decide if we can sink along it or need to break the edge.
1341   if (SuccToSinkTo->pred_size() > 1) {
1342     // We cannot sink a load across a critical edge - there may be stores in
1343     // other code paths.
1344     bool TryBreak = false;
1345     bool Store =
1346         MI.mayLoad() ? hasStoreBetween(ParentBlock, SuccToSinkTo, MI) : true;
1347     if (!MI.isSafeToMove(AA, Store)) {
1348       LLVM_DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
1349       TryBreak = true;
1350     }
1351 
1352     // We don't want to sink across a critical edge if we don't dominate the
1353     // successor. We could be introducing calculations to new code paths.
1354     if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
1355       LLVM_DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
1356       TryBreak = true;
1357     }
1358 
1359     // Don't sink instructions into a loop.
1360     if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
1361       LLVM_DEBUG(dbgs() << " *** NOTE: Loop header found\n");
1362       TryBreak = true;
1363     }
1364 
1365     // Otherwise we are OK with sinking along a critical edge.
1366     if (!TryBreak)
1367       LLVM_DEBUG(dbgs() << "Sinking along critical edge.\n");
1368     else {
1369       // Mark this edge as to be split.
1370       // If the edge can actually be split, the next iteration of the main loop
1371       // will sink MI in the newly created block.
1372       bool Status =
1373         PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
1374       if (!Status)
1375         LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
1376                              "break critical edge\n");
1377       // The instruction will not be sunk this time.
1378       return false;
1379     }
1380   }
1381 
1382   if (BreakPHIEdge) {
1383     // BreakPHIEdge is true if all the uses are in the successor MBB being
1384     // sunken into and they are all PHI nodes. In this case, machine-sink must
1385     // break the critical edge first.
1386     bool Status = PostponeSplitCriticalEdge(MI, ParentBlock,
1387                                             SuccToSinkTo, BreakPHIEdge);
1388     if (!Status)
1389       LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
1390                            "break critical edge\n");
1391     // The instruction will not be sunk this time.
1392     return false;
1393   }
1394 
1395   // Determine where to insert into. Skip phi nodes.
1396   MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
1397   while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
1398     ++InsertPos;
1399 
1400   // Collect debug users of any vreg that this inst defines.
1401   SmallVector<MIRegs, 4> DbgUsersToSink;
1402   for (auto &MO : MI.operands()) {
1403     if (!MO.isReg() || !MO.isDef() || !MO.getReg().isVirtual())
1404       continue;
1405     if (!SeenDbgUsers.count(MO.getReg()))
1406       continue;
1407 
1408     // Sink any users that don't pass any other DBG_VALUEs for this variable.
1409     auto &Users = SeenDbgUsers[MO.getReg()];
1410     for (auto &User : Users) {
1411       MachineInstr *DbgMI = User.getPointer();
1412       if (User.getInt()) {
1413         // This DBG_VALUE would re-order assignments. If we can't copy-propagate
1414         // it, it can't be recovered. Set it undef.
1415         if (!attemptDebugCopyProp(MI, *DbgMI, MO.getReg()))
1416           DbgMI->setDebugValueUndef();
1417       } else {
1418         DbgUsersToSink.push_back(
1419             {DbgMI, SmallVector<unsigned, 2>(1, MO.getReg())});
1420       }
1421     }
1422   }
1423 
1424   // After sinking, some debug users may not be dominated any more. If possible,
1425   // copy-propagate their operands. As it's expensive, don't do this if there's
1426   // no debuginfo in the program.
1427   if (MI.getMF()->getFunction().getSubprogram() && MI.isCopy())
1428     SalvageUnsunkDebugUsersOfCopy(MI, SuccToSinkTo);
1429 
1430   performSink(MI, *SuccToSinkTo, InsertPos, DbgUsersToSink);
1431 
1432   // Conservatively, clear any kill flags, since it's possible that they are no
1433   // longer correct.
1434   // Note that we have to clear the kill flags for any register this instruction
1435   // uses as we may sink over another instruction which currently kills the
1436   // used registers.
1437   for (MachineOperand &MO : MI.operands()) {
1438     if (MO.isReg() && MO.isUse())
1439       RegsToClearKillFlags.insert(MO.getReg()); // Remember to clear kill flags.
1440   }
1441 
1442   return true;
1443 }
1444 
1445 void MachineSinking::SalvageUnsunkDebugUsersOfCopy(
1446     MachineInstr &MI, MachineBasicBlock *TargetBlock) {
1447   assert(MI.isCopy());
1448   assert(MI.getOperand(1).isReg());
1449 
1450   // Enumerate all users of vreg operands that are def'd. Skip those that will
1451   // be sunk. For the rest, if they are not dominated by the block we will sink
1452   // MI into, propagate the copy source to them.
1453   SmallVector<MachineInstr *, 4> DbgDefUsers;
1454   SmallVector<Register, 4> DbgUseRegs;
1455   const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1456   for (auto &MO : MI.operands()) {
1457     if (!MO.isReg() || !MO.isDef() || !MO.getReg().isVirtual())
1458       continue;
1459     DbgUseRegs.push_back(MO.getReg());
1460     for (auto &User : MRI.use_instructions(MO.getReg())) {
1461       if (!User.isDebugValue() || DT->dominates(TargetBlock, User.getParent()))
1462         continue;
1463 
1464       // If is in same block, will either sink or be use-before-def.
1465       if (User.getParent() == MI.getParent())
1466         continue;
1467 
1468       assert(User.hasDebugOperandForReg(MO.getReg()) &&
1469              "DBG_VALUE user of vreg, but has no operand for it?");
1470       DbgDefUsers.push_back(&User);
1471     }
1472   }
1473 
1474   // Point the users of this copy that are no longer dominated, at the source
1475   // of the copy.
1476   for (auto *User : DbgDefUsers) {
1477     for (auto &Reg : DbgUseRegs) {
1478       for (auto &DbgOp : User->getDebugOperandsForReg(Reg)) {
1479         DbgOp.setReg(MI.getOperand(1).getReg());
1480         DbgOp.setSubReg(MI.getOperand(1).getSubReg());
1481       }
1482     }
1483   }
1484 }
1485 
1486 //===----------------------------------------------------------------------===//
1487 // This pass is not intended to be a replacement or a complete alternative
1488 // for the pre-ra machine sink pass. It is only designed to sink COPY
1489 // instructions which should be handled after RA.
1490 //
1491 // This pass sinks COPY instructions into a successor block, if the COPY is not
1492 // used in the current block and the COPY is live-in to a single successor
1493 // (i.e., doesn't require the COPY to be duplicated).  This avoids executing the
1494 // copy on paths where their results aren't needed.  This also exposes
1495 // additional opportunites for dead copy elimination and shrink wrapping.
1496 //
1497 // These copies were either not handled by or are inserted after the MachineSink
1498 // pass. As an example of the former case, the MachineSink pass cannot sink
1499 // COPY instructions with allocatable source registers; for AArch64 these type
1500 // of copy instructions are frequently used to move function parameters (PhyReg)
1501 // into virtual registers in the entry block.
1502 //
1503 // For the machine IR below, this pass will sink %w19 in the entry into its
1504 // successor (%bb.1) because %w19 is only live-in in %bb.1.
1505 // %bb.0:
1506 //   %wzr = SUBSWri %w1, 1
1507 //   %w19 = COPY %w0
1508 //   Bcc 11, %bb.2
1509 // %bb.1:
1510 //   Live Ins: %w19
1511 //   BL @fun
1512 //   %w0 = ADDWrr %w0, %w19
1513 //   RET %w0
1514 // %bb.2:
1515 //   %w0 = COPY %wzr
1516 //   RET %w0
1517 // As we sink %w19 (CSR in AArch64) into %bb.1, the shrink-wrapping pass will be
1518 // able to see %bb.0 as a candidate.
1519 //===----------------------------------------------------------------------===//
1520 namespace {
1521 
1522 class PostRAMachineSinking : public MachineFunctionPass {
1523 public:
1524   bool runOnMachineFunction(MachineFunction &MF) override;
1525 
1526   static char ID;
1527   PostRAMachineSinking() : MachineFunctionPass(ID) {}
1528   StringRef getPassName() const override { return "PostRA Machine Sink"; }
1529 
1530   void getAnalysisUsage(AnalysisUsage &AU) const override {
1531     AU.setPreservesCFG();
1532     MachineFunctionPass::getAnalysisUsage(AU);
1533   }
1534 
1535   MachineFunctionProperties getRequiredProperties() const override {
1536     return MachineFunctionProperties().set(
1537         MachineFunctionProperties::Property::NoVRegs);
1538   }
1539 
1540 private:
1541   /// Track which register units have been modified and used.
1542   LiveRegUnits ModifiedRegUnits, UsedRegUnits;
1543 
1544   /// Track DBG_VALUEs of (unmodified) register units. Each DBG_VALUE has an
1545   /// entry in this map for each unit it touches. The DBG_VALUE's entry
1546   /// consists of a pointer to the instruction itself, and a vector of registers
1547   /// referred to by the instruction that overlap the key register unit.
1548   DenseMap<unsigned, SmallVector<MIRegs, 2>> SeenDbgInstrs;
1549 
1550   /// Sink Copy instructions unused in the same block close to their uses in
1551   /// successors.
1552   bool tryToSinkCopy(MachineBasicBlock &BB, MachineFunction &MF,
1553                      const TargetRegisterInfo *TRI, const TargetInstrInfo *TII);
1554 };
1555 } // namespace
1556 
1557 char PostRAMachineSinking::ID = 0;
1558 char &llvm::PostRAMachineSinkingID = PostRAMachineSinking::ID;
1559 
1560 INITIALIZE_PASS(PostRAMachineSinking, "postra-machine-sink",
1561                 "PostRA Machine Sink", false, false)
1562 
1563 static bool aliasWithRegsInLiveIn(MachineBasicBlock &MBB, unsigned Reg,
1564                                   const TargetRegisterInfo *TRI) {
1565   LiveRegUnits LiveInRegUnits(*TRI);
1566   LiveInRegUnits.addLiveIns(MBB);
1567   return !LiveInRegUnits.available(Reg);
1568 }
1569 
1570 static MachineBasicBlock *
1571 getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
1572                       const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
1573                       unsigned Reg, const TargetRegisterInfo *TRI) {
1574   // Try to find a single sinkable successor in which Reg is live-in.
1575   MachineBasicBlock *BB = nullptr;
1576   for (auto *SI : SinkableBBs) {
1577     if (aliasWithRegsInLiveIn(*SI, Reg, TRI)) {
1578       // If BB is set here, Reg is live-in to at least two sinkable successors,
1579       // so quit.
1580       if (BB)
1581         return nullptr;
1582       BB = SI;
1583     }
1584   }
1585   // Reg is not live-in to any sinkable successors.
1586   if (!BB)
1587     return nullptr;
1588 
1589   // Check if any register aliased with Reg is live-in in other successors.
1590   for (auto *SI : CurBB.successors()) {
1591     if (!SinkableBBs.count(SI) && aliasWithRegsInLiveIn(*SI, Reg, TRI))
1592       return nullptr;
1593   }
1594   return BB;
1595 }
1596 
1597 static MachineBasicBlock *
1598 getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
1599                       const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
1600                       ArrayRef<unsigned> DefedRegsInCopy,
1601                       const TargetRegisterInfo *TRI) {
1602   MachineBasicBlock *SingleBB = nullptr;
1603   for (auto DefReg : DefedRegsInCopy) {
1604     MachineBasicBlock *BB =
1605         getSingleLiveInSuccBB(CurBB, SinkableBBs, DefReg, TRI);
1606     if (!BB || (SingleBB && SingleBB != BB))
1607       return nullptr;
1608     SingleBB = BB;
1609   }
1610   return SingleBB;
1611 }
1612 
1613 static void clearKillFlags(MachineInstr *MI, MachineBasicBlock &CurBB,
1614                            SmallVectorImpl<unsigned> &UsedOpsInCopy,
1615                            LiveRegUnits &UsedRegUnits,
1616                            const TargetRegisterInfo *TRI) {
1617   for (auto U : UsedOpsInCopy) {
1618     MachineOperand &MO = MI->getOperand(U);
1619     Register SrcReg = MO.getReg();
1620     if (!UsedRegUnits.available(SrcReg)) {
1621       MachineBasicBlock::iterator NI = std::next(MI->getIterator());
1622       for (MachineInstr &UI : make_range(NI, CurBB.end())) {
1623         if (UI.killsRegister(SrcReg, TRI)) {
1624           UI.clearRegisterKills(SrcReg, TRI);
1625           MO.setIsKill(true);
1626           break;
1627         }
1628       }
1629     }
1630   }
1631 }
1632 
1633 static void updateLiveIn(MachineInstr *MI, MachineBasicBlock *SuccBB,
1634                          SmallVectorImpl<unsigned> &UsedOpsInCopy,
1635                          SmallVectorImpl<unsigned> &DefedRegsInCopy) {
1636   MachineFunction &MF = *SuccBB->getParent();
1637   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1638   for (unsigned DefReg : DefedRegsInCopy)
1639     for (MCSubRegIterator S(DefReg, TRI, true); S.isValid(); ++S)
1640       SuccBB->removeLiveIn(*S);
1641   for (auto U : UsedOpsInCopy) {
1642     Register SrcReg = MI->getOperand(U).getReg();
1643     LaneBitmask Mask;
1644     for (MCRegUnitMaskIterator S(SrcReg, TRI); S.isValid(); ++S) {
1645       Mask |= (*S).second;
1646     }
1647     SuccBB->addLiveIn(SrcReg, Mask.any() ? Mask : LaneBitmask::getAll());
1648   }
1649   SuccBB->sortUniqueLiveIns();
1650 }
1651 
1652 static bool hasRegisterDependency(MachineInstr *MI,
1653                                   SmallVectorImpl<unsigned> &UsedOpsInCopy,
1654                                   SmallVectorImpl<unsigned> &DefedRegsInCopy,
1655                                   LiveRegUnits &ModifiedRegUnits,
1656                                   LiveRegUnits &UsedRegUnits) {
1657   bool HasRegDependency = false;
1658   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1659     MachineOperand &MO = MI->getOperand(i);
1660     if (!MO.isReg())
1661       continue;
1662     Register Reg = MO.getReg();
1663     if (!Reg)
1664       continue;
1665     if (MO.isDef()) {
1666       if (!ModifiedRegUnits.available(Reg) || !UsedRegUnits.available(Reg)) {
1667         HasRegDependency = true;
1668         break;
1669       }
1670       DefedRegsInCopy.push_back(Reg);
1671 
1672       // FIXME: instead of isUse(), readsReg() would be a better fix here,
1673       // For example, we can ignore modifications in reg with undef. However,
1674       // it's not perfectly clear if skipping the internal read is safe in all
1675       // other targets.
1676     } else if (MO.isUse()) {
1677       if (!ModifiedRegUnits.available(Reg)) {
1678         HasRegDependency = true;
1679         break;
1680       }
1681       UsedOpsInCopy.push_back(i);
1682     }
1683   }
1684   return HasRegDependency;
1685 }
1686 
1687 static SmallSet<MCRegister, 4> getRegUnits(MCRegister Reg,
1688                                            const TargetRegisterInfo *TRI) {
1689   SmallSet<MCRegister, 4> RegUnits;
1690   for (auto RI = MCRegUnitIterator(Reg, TRI); RI.isValid(); ++RI)
1691     RegUnits.insert(*RI);
1692   return RegUnits;
1693 }
1694 
1695 bool PostRAMachineSinking::tryToSinkCopy(MachineBasicBlock &CurBB,
1696                                          MachineFunction &MF,
1697                                          const TargetRegisterInfo *TRI,
1698                                          const TargetInstrInfo *TII) {
1699   SmallPtrSet<MachineBasicBlock *, 2> SinkableBBs;
1700   // FIXME: For now, we sink only to a successor which has a single predecessor
1701   // so that we can directly sink COPY instructions to the successor without
1702   // adding any new block or branch instruction.
1703   for (MachineBasicBlock *SI : CurBB.successors())
1704     if (!SI->livein_empty() && SI->pred_size() == 1)
1705       SinkableBBs.insert(SI);
1706 
1707   if (SinkableBBs.empty())
1708     return false;
1709 
1710   bool Changed = false;
1711 
1712   // Track which registers have been modified and used between the end of the
1713   // block and the current instruction.
1714   ModifiedRegUnits.clear();
1715   UsedRegUnits.clear();
1716   SeenDbgInstrs.clear();
1717 
1718   for (MachineInstr &MI : llvm::make_early_inc_range(llvm::reverse(CurBB))) {
1719     // Track the operand index for use in Copy.
1720     SmallVector<unsigned, 2> UsedOpsInCopy;
1721     // Track the register number defed in Copy.
1722     SmallVector<unsigned, 2> DefedRegsInCopy;
1723 
1724     // We must sink this DBG_VALUE if its operand is sunk. To avoid searching
1725     // for DBG_VALUEs later, record them when they're encountered.
1726     if (MI.isDebugValue()) {
1727       SmallDenseMap<MCRegister, SmallVector<unsigned, 2>, 4> MIUnits;
1728       bool IsValid = true;
1729       for (MachineOperand &MO : MI.debug_operands()) {
1730         if (MO.isReg() && Register::isPhysicalRegister(MO.getReg())) {
1731           // Bail if we can already tell the sink would be rejected, rather
1732           // than needlessly accumulating lots of DBG_VALUEs.
1733           if (hasRegisterDependency(&MI, UsedOpsInCopy, DefedRegsInCopy,
1734                                     ModifiedRegUnits, UsedRegUnits)) {
1735             IsValid = false;
1736             break;
1737           }
1738 
1739           // Record debug use of each reg unit.
1740           SmallSet<MCRegister, 4> RegUnits = getRegUnits(MO.getReg(), TRI);
1741           for (MCRegister Reg : RegUnits)
1742             MIUnits[Reg].push_back(MO.getReg());
1743         }
1744       }
1745       if (IsValid) {
1746         for (auto RegOps : MIUnits)
1747           SeenDbgInstrs[RegOps.first].push_back({&MI, RegOps.second});
1748       }
1749       continue;
1750     }
1751 
1752     if (MI.isDebugOrPseudoInstr())
1753       continue;
1754 
1755     // Do not move any instruction across function call.
1756     if (MI.isCall())
1757       return false;
1758 
1759     if (!MI.isCopy() || !MI.getOperand(0).isRenamable()) {
1760       LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
1761                                         TRI);
1762       continue;
1763     }
1764 
1765     // Don't sink the COPY if it would violate a register dependency.
1766     if (hasRegisterDependency(&MI, UsedOpsInCopy, DefedRegsInCopy,
1767                               ModifiedRegUnits, UsedRegUnits)) {
1768       LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
1769                                         TRI);
1770       continue;
1771     }
1772     assert((!UsedOpsInCopy.empty() && !DefedRegsInCopy.empty()) &&
1773            "Unexpect SrcReg or DefReg");
1774     MachineBasicBlock *SuccBB =
1775         getSingleLiveInSuccBB(CurBB, SinkableBBs, DefedRegsInCopy, TRI);
1776     // Don't sink if we cannot find a single sinkable successor in which Reg
1777     // is live-in.
1778     if (!SuccBB) {
1779       LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
1780                                         TRI);
1781       continue;
1782     }
1783     assert((SuccBB->pred_size() == 1 && *SuccBB->pred_begin() == &CurBB) &&
1784            "Unexpected predecessor");
1785 
1786     // Collect DBG_VALUEs that must sink with this copy. We've previously
1787     // recorded which reg units that DBG_VALUEs read, if this instruction
1788     // writes any of those units then the corresponding DBG_VALUEs must sink.
1789     MapVector<MachineInstr *, MIRegs::second_type> DbgValsToSinkMap;
1790     for (auto &MO : MI.operands()) {
1791       if (!MO.isReg() || !MO.isDef())
1792         continue;
1793 
1794       SmallSet<MCRegister, 4> Units = getRegUnits(MO.getReg(), TRI);
1795       for (MCRegister Reg : Units) {
1796         for (auto MIRegs : SeenDbgInstrs.lookup(Reg)) {
1797           auto &Regs = DbgValsToSinkMap[MIRegs.first];
1798           for (unsigned Reg : MIRegs.second)
1799             Regs.push_back(Reg);
1800         }
1801       }
1802     }
1803     SmallVector<MIRegs, 4> DbgValsToSink(DbgValsToSinkMap.begin(),
1804                                          DbgValsToSinkMap.end());
1805 
1806     // Clear the kill flag if SrcReg is killed between MI and the end of the
1807     // block.
1808     clearKillFlags(&MI, CurBB, UsedOpsInCopy, UsedRegUnits, TRI);
1809     MachineBasicBlock::iterator InsertPos = SuccBB->getFirstNonPHI();
1810     performSink(MI, *SuccBB, InsertPos, DbgValsToSink);
1811     updateLiveIn(&MI, SuccBB, UsedOpsInCopy, DefedRegsInCopy);
1812 
1813     Changed = true;
1814     ++NumPostRACopySink;
1815   }
1816   return Changed;
1817 }
1818 
1819 bool PostRAMachineSinking::runOnMachineFunction(MachineFunction &MF) {
1820   if (skipFunction(MF.getFunction()))
1821     return false;
1822 
1823   bool Changed = false;
1824   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1825   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
1826 
1827   ModifiedRegUnits.init(*TRI);
1828   UsedRegUnits.init(*TRI);
1829   for (auto &BB : MF)
1830     Changed |= tryToSinkCopy(BB, MF, TRI, TII);
1831 
1832   return Changed;
1833 }
1834