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