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