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