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