10b57cec5SDimitry Andric //===- MachineSink.cpp - Sinking for machine instructions -----------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This pass moves instructions into successor blocks when possible, so that
100b57cec5SDimitry Andric // they aren't executed on paths where their results aren't needed.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric // This pass is not intended to be a replacement or a complete alternative
130b57cec5SDimitry Andric // for an LLVM-IR-level sinking pass. It is only designed to sink simple
140b57cec5SDimitry Andric // constructs that are not exposed before lowering and instruction selection.
150b57cec5SDimitry Andric //
160b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
170b57cec5SDimitry Andric 
18480093f4SDimitry Andric #include "llvm/ADT/DenseSet.h"
1981ad6265SDimitry Andric #include "llvm/ADT/DepthFirstIterator.h"
20fe6060f1SDimitry Andric #include "llvm/ADT/MapVector.h"
21480093f4SDimitry Andric #include "llvm/ADT/PointerIntPair.h"
22fb03ea46SDimitry Andric #include "llvm/ADT/PostOrderIterator.h"
230b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
240b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
250b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
260b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
270b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
28fb03ea46SDimitry Andric #include "llvm/Analysis/CFG.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
300b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
310b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
3281ad6265SDimitry Andric #include "llvm/CodeGen/MachineCycleAnalysis.h"
330b57cec5SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
350b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
360b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
370b57cec5SDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h"
380b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
390b57cec5SDimitry Andric #include "llvm/CodeGen/MachinePostDominators.h"
400b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
41e8d8bef9SDimitry Andric #include "llvm/CodeGen/RegisterClassInfo.h"
42e8d8bef9SDimitry Andric #include "llvm/CodeGen/RegisterPressure.h"
430b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
44*c9157d92SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
450b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
460b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
470b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
480b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
498bcb0991SDimitry Andric #include "llvm/IR/LLVMContext.h"
50480093f4SDimitry Andric #include "llvm/InitializePasses.h"
518bcb0991SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
520b57cec5SDimitry Andric #include "llvm/Pass.h"
530b57cec5SDimitry Andric #include "llvm/Support/BranchProbability.h"
540b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
550b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
560b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
570b57cec5SDimitry Andric #include <algorithm>
580b57cec5SDimitry Andric #include <cassert>
590b57cec5SDimitry Andric #include <cstdint>
600b57cec5SDimitry Andric #include <utility>
610b57cec5SDimitry Andric #include <vector>
620b57cec5SDimitry Andric 
630b57cec5SDimitry Andric using namespace llvm;
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric #define DEBUG_TYPE "machine-sink"
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric static cl::opt<bool>
680b57cec5SDimitry Andric SplitEdges("machine-sink-split",
690b57cec5SDimitry Andric            cl::desc("Split critical edges during machine sinking"),
700b57cec5SDimitry Andric            cl::init(true), cl::Hidden);
710b57cec5SDimitry Andric 
720b57cec5SDimitry Andric static cl::opt<bool>
730b57cec5SDimitry Andric UseBlockFreqInfo("machine-sink-bfi",
740b57cec5SDimitry Andric            cl::desc("Use block frequency info to find successors to sink"),
750b57cec5SDimitry Andric            cl::init(true), cl::Hidden);
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric static cl::opt<unsigned> SplitEdgeProbabilityThreshold(
780b57cec5SDimitry Andric     "machine-sink-split-probability-threshold",
790b57cec5SDimitry Andric     cl::desc(
800b57cec5SDimitry Andric         "Percentage threshold for splitting single-instruction critical edge. "
810b57cec5SDimitry Andric         "If the branch threshold is higher than this threshold, we allow "
820b57cec5SDimitry Andric         "speculative execution of up to 1 instruction to avoid branching to "
830b57cec5SDimitry Andric         "splitted critical edge"),
840b57cec5SDimitry Andric     cl::init(40), cl::Hidden);
850b57cec5SDimitry Andric 
86e8d8bef9SDimitry Andric static cl::opt<unsigned> SinkLoadInstsPerBlockThreshold(
87e8d8bef9SDimitry Andric     "machine-sink-load-instrs-threshold",
88e8d8bef9SDimitry Andric     cl::desc("Do not try to find alias store for a load if there is a in-path "
89e8d8bef9SDimitry Andric              "block whose instruction number is higher than this threshold."),
90e8d8bef9SDimitry Andric     cl::init(2000), cl::Hidden);
91e8d8bef9SDimitry Andric 
92e8d8bef9SDimitry Andric static cl::opt<unsigned> SinkLoadBlocksThreshold(
93e8d8bef9SDimitry Andric     "machine-sink-load-blocks-threshold",
94e8d8bef9SDimitry Andric     cl::desc("Do not try to find alias store for a load if the block number in "
95e8d8bef9SDimitry Andric              "the straight line is higher than this threshold."),
96e8d8bef9SDimitry Andric     cl::init(20), cl::Hidden);
97e8d8bef9SDimitry Andric 
98fe6060f1SDimitry Andric static cl::opt<bool>
9981ad6265SDimitry Andric     SinkInstsIntoCycle("sink-insts-to-avoid-spills",
10081ad6265SDimitry Andric                        cl::desc("Sink instructions into cycles to avoid "
101fe6060f1SDimitry Andric                                 "register spills"),
102fe6060f1SDimitry Andric                        cl::init(false), cl::Hidden);
103fe6060f1SDimitry Andric 
10481ad6265SDimitry Andric static cl::opt<unsigned> SinkIntoCycleLimit(
10581ad6265SDimitry Andric     "machine-sink-cycle-limit",
10681ad6265SDimitry Andric     cl::desc("The maximum number of instructions considered for cycle sinking."),
107fe6060f1SDimitry Andric     cl::init(50), cl::Hidden);
108fe6060f1SDimitry Andric 
1090b57cec5SDimitry Andric STATISTIC(NumSunk,      "Number of machine instructions sunk");
11081ad6265SDimitry Andric STATISTIC(NumCycleSunk,  "Number of machine instructions sunk into a cycle");
1110b57cec5SDimitry Andric STATISTIC(NumSplit,     "Number of critical edges split");
1120b57cec5SDimitry Andric STATISTIC(NumCoalesces, "Number of copies coalesced");
1130b57cec5SDimitry Andric STATISTIC(NumPostRACopySink, "Number of copies sunk after RA");
1140b57cec5SDimitry Andric 
1150b57cec5SDimitry Andric namespace {
1160b57cec5SDimitry Andric 
1170b57cec5SDimitry Andric   class MachineSinking : public MachineFunctionPass {
118*c9157d92SDimitry Andric     const TargetSubtargetInfo *STI = nullptr;
119fe013be4SDimitry Andric     const TargetInstrInfo *TII = nullptr;
120fe013be4SDimitry Andric     const TargetRegisterInfo *TRI = nullptr;
121fe013be4SDimitry Andric     MachineRegisterInfo *MRI = nullptr;      // Machine register information
122fe013be4SDimitry Andric     MachineDominatorTree *DT = nullptr;      // Machine dominator tree
123fe013be4SDimitry Andric     MachinePostDominatorTree *PDT = nullptr; // Machine post dominator tree
124fe013be4SDimitry Andric     MachineCycleInfo *CI = nullptr;
125fe013be4SDimitry Andric     MachineBlockFrequencyInfo *MBFI = nullptr;
126fe013be4SDimitry Andric     const MachineBranchProbabilityInfo *MBPI = nullptr;
127fe013be4SDimitry Andric     AliasAnalysis *AA = nullptr;
128e8d8bef9SDimitry Andric     RegisterClassInfo RegClassInfo;
1290b57cec5SDimitry Andric 
1300b57cec5SDimitry Andric     // Remember which edges have been considered for breaking.
1310b57cec5SDimitry Andric     SmallSet<std::pair<MachineBasicBlock*, MachineBasicBlock*>, 8>
1320b57cec5SDimitry Andric     CEBCandidates;
1330b57cec5SDimitry Andric     // Remember which edges we are about to split.
1340b57cec5SDimitry Andric     // This is different from CEBCandidates since those edges
1350b57cec5SDimitry Andric     // will be split.
1360b57cec5SDimitry Andric     SetVector<std::pair<MachineBasicBlock *, MachineBasicBlock *>> ToSplit;
1370b57cec5SDimitry Andric 
138349cc55cSDimitry Andric     DenseSet<Register> RegsToClearKillFlags;
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric     using AllSuccsCache =
141*c9157d92SDimitry Andric         DenseMap<MachineBasicBlock *, SmallVector<MachineBasicBlock *, 4>>;
1420b57cec5SDimitry Andric 
143480093f4SDimitry Andric     /// DBG_VALUE pointer and flag. The flag is true if this DBG_VALUE is
144480093f4SDimitry Andric     /// post-dominated by another DBG_VALUE of the same variable location.
145480093f4SDimitry Andric     /// This is necessary to detect sequences such as:
146480093f4SDimitry Andric     ///     %0 = someinst
147480093f4SDimitry Andric     ///     DBG_VALUE %0, !123, !DIExpression()
148480093f4SDimitry Andric     ///     %1 = anotherinst
149480093f4SDimitry Andric     ///     DBG_VALUE %1, !123, !DIExpression()
150480093f4SDimitry Andric     /// Where if %0 were to sink, the DBG_VAUE should not sink with it, as that
151480093f4SDimitry Andric     /// would re-order assignments.
152480093f4SDimitry Andric     using SeenDbgUser = PointerIntPair<MachineInstr *, 1>;
153480093f4SDimitry Andric 
154480093f4SDimitry Andric     /// Record of DBG_VALUE uses of vregs in a block, so that we can identify
155480093f4SDimitry Andric     /// debug instructions to sink.
156480093f4SDimitry Andric     SmallDenseMap<unsigned, TinyPtrVector<SeenDbgUser>> SeenDbgUsers;
157480093f4SDimitry Andric 
158480093f4SDimitry Andric     /// Record of debug variables that have had their locations set in the
159480093f4SDimitry Andric     /// current block.
160480093f4SDimitry Andric     DenseSet<DebugVariable> SeenDbgVars;
161480093f4SDimitry Andric 
162*c9157d92SDimitry Andric     DenseMap<std::pair<MachineBasicBlock *, MachineBasicBlock *>, bool>
163e8d8bef9SDimitry Andric         HasStoreCache;
164*c9157d92SDimitry Andric 
165*c9157d92SDimitry Andric     DenseMap<std::pair<MachineBasicBlock *, MachineBasicBlock *>,
166*c9157d92SDimitry Andric              SmallVector<MachineInstr *>>
167e8d8bef9SDimitry Andric         StoreInstrCache;
168e8d8bef9SDimitry Andric 
169e8d8bef9SDimitry Andric     /// Cached BB's register pressure.
170*c9157d92SDimitry Andric     DenseMap<const MachineBasicBlock *, std::vector<unsigned>>
171*c9157d92SDimitry Andric         CachedRegisterPressure;
172*c9157d92SDimitry Andric 
173*c9157d92SDimitry Andric     bool EnableSinkAndFold;
174e8d8bef9SDimitry Andric 
1750b57cec5SDimitry Andric   public:
1760b57cec5SDimitry Andric     static char ID; // Pass identification
1770b57cec5SDimitry Andric 
MachineSinking()1780b57cec5SDimitry Andric     MachineSinking() : MachineFunctionPass(ID) {
1790b57cec5SDimitry Andric       initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
1800b57cec5SDimitry Andric     }
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric     bool runOnMachineFunction(MachineFunction &MF) override;
1830b57cec5SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const1840b57cec5SDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
1850b57cec5SDimitry Andric       MachineFunctionPass::getAnalysisUsage(AU);
1860b57cec5SDimitry Andric       AU.addRequired<AAResultsWrapperPass>();
1870b57cec5SDimitry Andric       AU.addRequired<MachineDominatorTree>();
1880b57cec5SDimitry Andric       AU.addRequired<MachinePostDominatorTree>();
18981ad6265SDimitry Andric       AU.addRequired<MachineCycleInfoWrapperPass>();
1900b57cec5SDimitry Andric       AU.addRequired<MachineBranchProbabilityInfo>();
19181ad6265SDimitry Andric       AU.addPreserved<MachineCycleInfoWrapperPass>();
1920b57cec5SDimitry Andric       AU.addPreserved<MachineLoopInfo>();
1930b57cec5SDimitry Andric       if (UseBlockFreqInfo)
1940b57cec5SDimitry Andric         AU.addRequired<MachineBlockFrequencyInfo>();
195*c9157d92SDimitry Andric       AU.addRequired<TargetPassConfig>();
1960b57cec5SDimitry Andric     }
1970b57cec5SDimitry Andric 
releaseMemory()1980b57cec5SDimitry Andric     void releaseMemory() override {
1990b57cec5SDimitry Andric       CEBCandidates.clear();
2000b57cec5SDimitry Andric     }
2010b57cec5SDimitry Andric 
2020b57cec5SDimitry Andric   private:
2030b57cec5SDimitry Andric     bool ProcessBlock(MachineBasicBlock &MBB);
204480093f4SDimitry Andric     void ProcessDbgInst(MachineInstr &MI);
2050b57cec5SDimitry Andric     bool isWorthBreakingCriticalEdge(MachineInstr &MI,
2060b57cec5SDimitry Andric                                      MachineBasicBlock *From,
2070b57cec5SDimitry Andric                                      MachineBasicBlock *To);
2080b57cec5SDimitry Andric 
209e8d8bef9SDimitry Andric     bool hasStoreBetween(MachineBasicBlock *From, MachineBasicBlock *To,
210e8d8bef9SDimitry Andric                          MachineInstr &MI);
211e8d8bef9SDimitry Andric 
2120b57cec5SDimitry Andric     /// Postpone the splitting of the given critical
2130b57cec5SDimitry Andric     /// edge (\p From, \p To).
2140b57cec5SDimitry Andric     ///
2150b57cec5SDimitry Andric     /// We do not split the edges on the fly. Indeed, this invalidates
2160b57cec5SDimitry Andric     /// the dominance information and thus triggers a lot of updates
2170b57cec5SDimitry Andric     /// of that information underneath.
2180b57cec5SDimitry Andric     /// Instead, we postpone all the splits after each iteration of
2190b57cec5SDimitry Andric     /// the main loop. That way, the information is at least valid
2200b57cec5SDimitry Andric     /// for the lifetime of an iteration.
2210b57cec5SDimitry Andric     ///
2220b57cec5SDimitry Andric     /// \return True if the edge is marked as toSplit, false otherwise.
2230b57cec5SDimitry Andric     /// False can be returned if, for instance, this is not profitable.
2240b57cec5SDimitry Andric     bool PostponeSplitCriticalEdge(MachineInstr &MI,
2250b57cec5SDimitry Andric                                    MachineBasicBlock *From,
2260b57cec5SDimitry Andric                                    MachineBasicBlock *To,
2270b57cec5SDimitry Andric                                    bool BreakPHIEdge);
2280b57cec5SDimitry Andric     bool SinkInstruction(MachineInstr &MI, bool &SawStore,
2290b57cec5SDimitry Andric                          AllSuccsCache &AllSuccessors);
230480093f4SDimitry Andric 
231480093f4SDimitry Andric     /// If we sink a COPY inst, some debug users of it's destination may no
232480093f4SDimitry Andric     /// longer be dominated by the COPY, and will eventually be dropped.
233480093f4SDimitry Andric     /// This is easily rectified by forwarding the non-dominated debug uses
234480093f4SDimitry Andric     /// to the copy source.
235480093f4SDimitry Andric     void SalvageUnsunkDebugUsersOfCopy(MachineInstr &,
236480093f4SDimitry Andric                                        MachineBasicBlock *TargetBlock);
237e8d8bef9SDimitry Andric     bool AllUsesDominatedByBlock(Register Reg, MachineBasicBlock *MBB,
238e8d8bef9SDimitry Andric                                  MachineBasicBlock *DefMBB, bool &BreakPHIEdge,
239e8d8bef9SDimitry Andric                                  bool &LocalUse) const;
2400b57cec5SDimitry Andric     MachineBasicBlock *FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
2410b57cec5SDimitry Andric                bool &BreakPHIEdge, AllSuccsCache &AllSuccessors);
242fe6060f1SDimitry Andric 
24381ad6265SDimitry Andric     void FindCycleSinkCandidates(MachineCycle *Cycle, MachineBasicBlock *BB,
244fe6060f1SDimitry Andric                                  SmallVectorImpl<MachineInstr *> &Candidates);
24581ad6265SDimitry Andric     bool SinkIntoCycle(MachineCycle *Cycle, MachineInstr &I);
246fe6060f1SDimitry Andric 
247e8d8bef9SDimitry Andric     bool isProfitableToSinkTo(Register Reg, MachineInstr &MI,
2480b57cec5SDimitry Andric                               MachineBasicBlock *MBB,
2490b57cec5SDimitry Andric                               MachineBasicBlock *SuccToSinkTo,
2500b57cec5SDimitry Andric                               AllSuccsCache &AllSuccessors);
2510b57cec5SDimitry Andric 
2520b57cec5SDimitry Andric     bool PerformTrivialForwardCoalescing(MachineInstr &MI,
2530b57cec5SDimitry Andric                                          MachineBasicBlock *MBB);
2540b57cec5SDimitry Andric 
255*c9157d92SDimitry Andric     bool PerformSinkAndFold(MachineInstr &MI, MachineBasicBlock *MBB);
256*c9157d92SDimitry Andric 
2570b57cec5SDimitry Andric     SmallVector<MachineBasicBlock *, 4> &
2580b57cec5SDimitry Andric     GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
2590b57cec5SDimitry Andric                            AllSuccsCache &AllSuccessors) const;
260e8d8bef9SDimitry Andric 
261*c9157d92SDimitry Andric     std::vector<unsigned> &getBBRegisterPressure(const MachineBasicBlock &MBB);
262*c9157d92SDimitry Andric 
263*c9157d92SDimitry Andric     bool registerPressureSetExceedsLimit(unsigned NRegs,
264*c9157d92SDimitry Andric                                          const TargetRegisterClass *RC,
265*c9157d92SDimitry Andric                                          const MachineBasicBlock &MBB);
2660b57cec5SDimitry Andric   };
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric } // end anonymous namespace
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric char MachineSinking::ID = 0;
2710b57cec5SDimitry Andric 
2720b57cec5SDimitry Andric char &llvm::MachineSinkingID = MachineSinking::ID;
2730b57cec5SDimitry Andric 
2740b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(MachineSinking, DEBUG_TYPE,
2750b57cec5SDimitry Andric                       "Machine code sinking", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)2760b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
2770b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
27881ad6265SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineCycleInfoWrapperPass)
2790b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2800b57cec5SDimitry Andric INITIALIZE_PASS_END(MachineSinking, DEBUG_TYPE,
2810b57cec5SDimitry Andric                     "Machine code sinking", false, false)
2820b57cec5SDimitry Andric 
283fe013be4SDimitry Andric /// Return true if a target defined block prologue instruction interferes
284fe013be4SDimitry Andric /// with a sink candidate.
285fe013be4SDimitry Andric static bool blockPrologueInterferes(const MachineBasicBlock *BB,
286fe013be4SDimitry Andric                                     MachineBasicBlock::const_iterator End,
287fe013be4SDimitry Andric                                     const MachineInstr &MI,
288fe013be4SDimitry Andric                                     const TargetRegisterInfo *TRI,
289fe013be4SDimitry Andric                                     const TargetInstrInfo *TII,
290fe013be4SDimitry Andric                                     const MachineRegisterInfo *MRI) {
291fe013be4SDimitry Andric   for (MachineBasicBlock::const_iterator PI = BB->getFirstNonPHI(); PI != End;
292fe013be4SDimitry Andric        ++PI) {
293fe013be4SDimitry Andric     // Only check target defined prologue instructions
294fe013be4SDimitry Andric     if (!TII->isBasicBlockPrologue(*PI))
295fe013be4SDimitry Andric       continue;
296fe013be4SDimitry Andric     for (auto &MO : MI.operands()) {
297fe013be4SDimitry Andric       if (!MO.isReg())
298fe013be4SDimitry Andric         continue;
299fe013be4SDimitry Andric       Register Reg = MO.getReg();
300fe013be4SDimitry Andric       if (!Reg)
301fe013be4SDimitry Andric         continue;
302fe013be4SDimitry Andric       if (MO.isUse()) {
303*c9157d92SDimitry Andric         if (Reg.isPhysical() &&
304*c9157d92SDimitry Andric             (TII->isIgnorableUse(MO) || (MRI && MRI->isConstantPhysReg(Reg))))
305fe013be4SDimitry Andric           continue;
306fe013be4SDimitry Andric         if (PI->modifiesRegister(Reg, TRI))
307fe013be4SDimitry Andric           return true;
308fe013be4SDimitry Andric       } else {
309fe013be4SDimitry Andric         if (PI->readsRegister(Reg, TRI))
310fe013be4SDimitry Andric           return true;
311fe013be4SDimitry Andric         // Check for interference with non-dead defs
312fe013be4SDimitry Andric         auto *DefOp = PI->findRegisterDefOperand(Reg, false, true, TRI);
313fe013be4SDimitry Andric         if (DefOp && !DefOp->isDead())
314fe013be4SDimitry Andric           return true;
315fe013be4SDimitry Andric       }
316fe013be4SDimitry Andric     }
317fe013be4SDimitry Andric   }
318fe013be4SDimitry Andric 
319fe013be4SDimitry Andric   return false;
320fe013be4SDimitry Andric }
321fe013be4SDimitry Andric 
PerformTrivialForwardCoalescing(MachineInstr & MI,MachineBasicBlock * MBB)3220b57cec5SDimitry Andric bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr &MI,
3230b57cec5SDimitry Andric                                                      MachineBasicBlock *MBB) {
3240b57cec5SDimitry Andric   if (!MI.isCopy())
3250b57cec5SDimitry Andric     return false;
3260b57cec5SDimitry Andric 
3278bcb0991SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
3288bcb0991SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
329bdd1243dSDimitry Andric   if (!SrcReg.isVirtual() || !DstReg.isVirtual() ||
330bdd1243dSDimitry Andric       !MRI->hasOneNonDBGUse(SrcReg))
3310b57cec5SDimitry Andric     return false;
3320b57cec5SDimitry Andric 
3330b57cec5SDimitry Andric   const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
3340b57cec5SDimitry Andric   const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
3350b57cec5SDimitry Andric   if (SRC != DRC)
3360b57cec5SDimitry Andric     return false;
3370b57cec5SDimitry Andric 
3380b57cec5SDimitry Andric   MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
3390b57cec5SDimitry Andric   if (DefMI->isCopyLike())
3400b57cec5SDimitry Andric     return false;
3410b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI);
3420b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "*** to: " << MI);
3430b57cec5SDimitry Andric   MRI->replaceRegWith(DstReg, SrcReg);
3440b57cec5SDimitry Andric   MI.eraseFromParent();
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric   // Conservatively, clear any kill flags, since it's possible that they are no
3470b57cec5SDimitry Andric   // longer correct.
3480b57cec5SDimitry Andric   MRI->clearKillFlags(SrcReg);
3490b57cec5SDimitry Andric 
3500b57cec5SDimitry Andric   ++NumCoalesces;
3510b57cec5SDimitry Andric   return true;
3520b57cec5SDimitry Andric }
3530b57cec5SDimitry Andric 
PerformSinkAndFold(MachineInstr & MI,MachineBasicBlock * MBB)354*c9157d92SDimitry Andric bool MachineSinking::PerformSinkAndFold(MachineInstr &MI,
355*c9157d92SDimitry Andric                                         MachineBasicBlock *MBB) {
356*c9157d92SDimitry Andric   if (MI.isCopy() || MI.mayLoadOrStore() ||
357*c9157d92SDimitry Andric       MI.getOpcode() == TargetOpcode::REG_SEQUENCE)
358*c9157d92SDimitry Andric     return false;
359*c9157d92SDimitry Andric 
360*c9157d92SDimitry Andric   // Don't sink instructions that the target prefers not to sink.
361*c9157d92SDimitry Andric   if (!TII->shouldSink(MI))
362*c9157d92SDimitry Andric     return false;
363*c9157d92SDimitry Andric 
364*c9157d92SDimitry Andric   // Check if it's safe to move the instruction.
365*c9157d92SDimitry Andric   bool SawStore = true;
366*c9157d92SDimitry Andric   if (!MI.isSafeToMove(AA, SawStore))
367*c9157d92SDimitry Andric     return false;
368*c9157d92SDimitry Andric 
369*c9157d92SDimitry Andric   // Convergent operations may not be made control-dependent on additional
370*c9157d92SDimitry Andric   // values.
371*c9157d92SDimitry Andric   if (MI.isConvergent())
372*c9157d92SDimitry Andric     return false;
373*c9157d92SDimitry Andric 
374*c9157d92SDimitry Andric   // Don't sink defs/uses of hard registers or if the instruction defines more
375*c9157d92SDimitry Andric   // than one register.
376*c9157d92SDimitry Andric   // Don't sink more than two register uses - it'll cover most of the cases and
377*c9157d92SDimitry Andric   // greatly simplifies the register pressure checks.
378*c9157d92SDimitry Andric   Register DefReg;
379*c9157d92SDimitry Andric   Register UsedRegA, UsedRegB;
380*c9157d92SDimitry Andric   for (const MachineOperand &MO : MI.operands()) {
381*c9157d92SDimitry Andric     if (MO.isImm() || MO.isRegMask() || MO.isRegLiveOut() || MO.isMetadata() ||
382*c9157d92SDimitry Andric         MO.isMCSymbol() || MO.isDbgInstrRef() || MO.isCFIIndex() ||
383*c9157d92SDimitry Andric         MO.isIntrinsicID() || MO.isPredicate() || MO.isShuffleMask())
384*c9157d92SDimitry Andric       continue;
385*c9157d92SDimitry Andric     if (!MO.isReg())
386*c9157d92SDimitry Andric       return false;
387*c9157d92SDimitry Andric 
388*c9157d92SDimitry Andric     Register Reg = MO.getReg();
389*c9157d92SDimitry Andric     if (Reg == 0)
390*c9157d92SDimitry Andric       continue;
391*c9157d92SDimitry Andric 
392*c9157d92SDimitry Andric     if (Reg.isVirtual()) {
393*c9157d92SDimitry Andric       if (MO.isDef()) {
394*c9157d92SDimitry Andric         if (DefReg)
395*c9157d92SDimitry Andric           return false;
396*c9157d92SDimitry Andric         DefReg = Reg;
397*c9157d92SDimitry Andric         continue;
398*c9157d92SDimitry Andric       }
399*c9157d92SDimitry Andric 
400*c9157d92SDimitry Andric       if (UsedRegA == 0)
401*c9157d92SDimitry Andric         UsedRegA = Reg;
402*c9157d92SDimitry Andric       else if (UsedRegB == 0)
403*c9157d92SDimitry Andric         UsedRegB = Reg;
404*c9157d92SDimitry Andric       else
405*c9157d92SDimitry Andric         return false;
406*c9157d92SDimitry Andric       continue;
407*c9157d92SDimitry Andric     }
408*c9157d92SDimitry Andric 
409*c9157d92SDimitry Andric     if (Reg.isPhysical() &&
410*c9157d92SDimitry Andric         (MRI->isConstantPhysReg(Reg) || TII->isIgnorableUse(MO)))
411*c9157d92SDimitry Andric       continue;
412*c9157d92SDimitry Andric 
413*c9157d92SDimitry Andric     return false;
414*c9157d92SDimitry Andric   }
415*c9157d92SDimitry Andric 
416*c9157d92SDimitry Andric   // Scan uses of the destination register. Every use, except the last, must be
417*c9157d92SDimitry Andric   // a copy, with a chain of copies terminating with either a copy into a hard
418*c9157d92SDimitry Andric   // register, or a load/store instruction where the use is part of the
419*c9157d92SDimitry Andric   // address (*not* the stored value).
420*c9157d92SDimitry Andric   using SinkInfo = std::pair<MachineInstr *, ExtAddrMode>;
421*c9157d92SDimitry Andric   SmallVector<SinkInfo> SinkInto;
422*c9157d92SDimitry Andric   SmallVector<Register> Worklist;
423*c9157d92SDimitry Andric 
424*c9157d92SDimitry Andric   const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
425*c9157d92SDimitry Andric   const TargetRegisterClass *RCA =
426*c9157d92SDimitry Andric       UsedRegA == 0 ? nullptr : MRI->getRegClass(UsedRegA);
427*c9157d92SDimitry Andric   const TargetRegisterClass *RCB =
428*c9157d92SDimitry Andric       UsedRegB == 0 ? nullptr : MRI->getRegClass(UsedRegB);
429*c9157d92SDimitry Andric 
430*c9157d92SDimitry Andric   Worklist.push_back(DefReg);
431*c9157d92SDimitry Andric   while (!Worklist.empty()) {
432*c9157d92SDimitry Andric     Register Reg = Worklist.pop_back_val();
433*c9157d92SDimitry Andric 
434*c9157d92SDimitry Andric     for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
435*c9157d92SDimitry Andric       ExtAddrMode MaybeAM;
436*c9157d92SDimitry Andric       MachineInstr &UseInst = *MO.getParent();
437*c9157d92SDimitry Andric       if (UseInst.isCopy()) {
438*c9157d92SDimitry Andric         Register DstReg;
439*c9157d92SDimitry Andric         if (const MachineOperand &O = UseInst.getOperand(0); O.isReg())
440*c9157d92SDimitry Andric           DstReg = O.getReg();
441*c9157d92SDimitry Andric         if (DstReg == 0)
442*c9157d92SDimitry Andric           return false;
443*c9157d92SDimitry Andric         if (DstReg.isVirtual()) {
444*c9157d92SDimitry Andric           Worklist.push_back(DstReg);
445*c9157d92SDimitry Andric           continue;
446*c9157d92SDimitry Andric         }
447*c9157d92SDimitry Andric         // If we are going to replace a copy, the original instruction must be
448*c9157d92SDimitry Andric         // as cheap as a copy.
449*c9157d92SDimitry Andric         if (!TII->isAsCheapAsAMove(MI))
450*c9157d92SDimitry Andric           return false;
451*c9157d92SDimitry Andric         // The hard register must be in the register class of the original
452*c9157d92SDimitry Andric         // instruction's destination register.
453*c9157d92SDimitry Andric         if (!RC->contains(DstReg))
454*c9157d92SDimitry Andric           return false;
455*c9157d92SDimitry Andric       } else if (UseInst.mayLoadOrStore()) {
456*c9157d92SDimitry Andric         ExtAddrMode AM;
457*c9157d92SDimitry Andric         if (!TII->canFoldIntoAddrMode(UseInst, Reg, MI, AM))
458*c9157d92SDimitry Andric           return false;
459*c9157d92SDimitry Andric         MaybeAM = AM;
460*c9157d92SDimitry Andric       } else {
461*c9157d92SDimitry Andric         return false;
462*c9157d92SDimitry Andric       }
463*c9157d92SDimitry Andric 
464*c9157d92SDimitry Andric       if (UseInst.getParent() != MI.getParent()) {
465*c9157d92SDimitry Andric         // If the register class of the register we are replacing is a superset
466*c9157d92SDimitry Andric         // of any of the register classes of the operands of the materialized
467*c9157d92SDimitry Andric         // instruction don't consider that live range extended.
468*c9157d92SDimitry Andric         const TargetRegisterClass *RCS = MRI->getRegClass(Reg);
469*c9157d92SDimitry Andric         if (RCA && RCA->hasSuperClassEq(RCS))
470*c9157d92SDimitry Andric           RCA = nullptr;
471*c9157d92SDimitry Andric         else if (RCB && RCB->hasSuperClassEq(RCS))
472*c9157d92SDimitry Andric           RCB = nullptr;
473*c9157d92SDimitry Andric         if (RCA || RCB) {
474*c9157d92SDimitry Andric           if (RCA == nullptr) {
475*c9157d92SDimitry Andric             RCA = RCB;
476*c9157d92SDimitry Andric             RCB = nullptr;
477*c9157d92SDimitry Andric           }
478*c9157d92SDimitry Andric 
479*c9157d92SDimitry Andric           unsigned NRegs = !!RCA + !!RCB;
480*c9157d92SDimitry Andric           if (RCA == RCB)
481*c9157d92SDimitry Andric             RCB = nullptr;
482*c9157d92SDimitry Andric 
483*c9157d92SDimitry Andric           // Check we don't exceed register pressure at the destination.
484*c9157d92SDimitry Andric           const MachineBasicBlock &MBB = *UseInst.getParent();
485*c9157d92SDimitry Andric           if (RCB == nullptr) {
486*c9157d92SDimitry Andric             if (registerPressureSetExceedsLimit(NRegs, RCA, MBB))
487*c9157d92SDimitry Andric               return false;
488*c9157d92SDimitry Andric           } else if (registerPressureSetExceedsLimit(1, RCA, MBB) ||
489*c9157d92SDimitry Andric                      registerPressureSetExceedsLimit(1, RCB, MBB)) {
490*c9157d92SDimitry Andric             return false;
491*c9157d92SDimitry Andric           }
492*c9157d92SDimitry Andric         }
493*c9157d92SDimitry Andric       }
494*c9157d92SDimitry Andric 
495*c9157d92SDimitry Andric       SinkInto.emplace_back(&UseInst, MaybeAM);
496*c9157d92SDimitry Andric     }
497*c9157d92SDimitry Andric   }
498*c9157d92SDimitry Andric 
499*c9157d92SDimitry Andric   if (SinkInto.empty())
500*c9157d92SDimitry Andric     return false;
501*c9157d92SDimitry Andric 
502*c9157d92SDimitry Andric   // Now we know we can fold the instruction in all its users.
503*c9157d92SDimitry Andric   for (auto &[SinkDst, MaybeAM] : SinkInto) {
504*c9157d92SDimitry Andric     MachineInstr *New = nullptr;
505*c9157d92SDimitry Andric     LLVM_DEBUG(dbgs() << "Sinking copy of"; MI.dump(); dbgs() << "into";
506*c9157d92SDimitry Andric                SinkDst->dump());
507*c9157d92SDimitry Andric     if (SinkDst->isCopy()) {
508*c9157d92SDimitry Andric       // TODO: After performing the sink-and-fold, the original instruction is
509*c9157d92SDimitry Andric       // deleted. Its value is still available (in a hard register), so if there
510*c9157d92SDimitry Andric       // are debug instructions which refer to the (now deleted) virtual
511*c9157d92SDimitry Andric       // register they could be updated to refer to the hard register, in
512*c9157d92SDimitry Andric       // principle. However, it's not clear how to do that, moreover in some
513*c9157d92SDimitry Andric       // cases the debug instructions may need to be replicated proportionally
514*c9157d92SDimitry Andric       // to the number of the COPY instructions replaced and in some extreme
515*c9157d92SDimitry Andric       // cases we can end up with quadratic increase in the number of debug
516*c9157d92SDimitry Andric       // instructions.
517*c9157d92SDimitry Andric 
518*c9157d92SDimitry Andric       // Sink a copy of the instruction, replacing a COPY instruction.
519*c9157d92SDimitry Andric       MachineBasicBlock::iterator InsertPt = SinkDst->getIterator();
520*c9157d92SDimitry Andric       Register DstReg = SinkDst->getOperand(0).getReg();
521*c9157d92SDimitry Andric       TII->reMaterialize(*SinkDst->getParent(), InsertPt, DstReg, 0, MI, *TRI);
522*c9157d92SDimitry Andric       New = &*std::prev(InsertPt);
523*c9157d92SDimitry Andric       if (!New->getDebugLoc())
524*c9157d92SDimitry Andric         New->setDebugLoc(SinkDst->getDebugLoc());
525*c9157d92SDimitry Andric 
526*c9157d92SDimitry Andric       // The operand registers of the "sunk" instruction have their live range
527*c9157d92SDimitry Andric       // extended and their kill flags may no longer be correct. Conservatively
528*c9157d92SDimitry Andric       // clear the kill flags.
529*c9157d92SDimitry Andric       if (UsedRegA)
530*c9157d92SDimitry Andric         MRI->clearKillFlags(UsedRegA);
531*c9157d92SDimitry Andric       if (UsedRegB)
532*c9157d92SDimitry Andric         MRI->clearKillFlags(UsedRegB);
533*c9157d92SDimitry Andric     } else {
534*c9157d92SDimitry Andric       // Fold instruction into the addressing mode of a memory instruction.
535*c9157d92SDimitry Andric       New = TII->emitLdStWithAddr(*SinkDst, MaybeAM);
536*c9157d92SDimitry Andric 
537*c9157d92SDimitry Andric       // The registers of the addressing mode may have their live range extended
538*c9157d92SDimitry Andric       // and their kill flags may no longer be correct. Conservatively clear the
539*c9157d92SDimitry Andric       // kill flags.
540*c9157d92SDimitry Andric       if (Register R = MaybeAM.BaseReg; R.isValid() && R.isVirtual())
541*c9157d92SDimitry Andric         MRI->clearKillFlags(R);
542*c9157d92SDimitry Andric       if (Register R = MaybeAM.ScaledReg; R.isValid() && R.isVirtual())
543*c9157d92SDimitry Andric         MRI->clearKillFlags(R);
544*c9157d92SDimitry Andric     }
545*c9157d92SDimitry Andric     LLVM_DEBUG(dbgs() << "yielding"; New->dump());
546*c9157d92SDimitry Andric     // Clear the StoreInstrCache, since we may invalidate it by erasing.
547*c9157d92SDimitry Andric     if (SinkDst->mayStore() && !SinkDst->hasOrderedMemoryRef())
548*c9157d92SDimitry Andric       StoreInstrCache.clear();
549*c9157d92SDimitry Andric     SinkDst->eraseFromParent();
550*c9157d92SDimitry Andric   }
551*c9157d92SDimitry Andric 
552*c9157d92SDimitry Andric   // Collect operands that need to be cleaned up because the registers no longer
553*c9157d92SDimitry Andric   // exist (in COPYs and debug instructions). We cannot delete instructions or
554*c9157d92SDimitry Andric   // clear operands while traversing register uses.
555*c9157d92SDimitry Andric   SmallVector<MachineOperand *> Cleanup;
556*c9157d92SDimitry Andric   Worklist.push_back(DefReg);
557*c9157d92SDimitry Andric   while (!Worklist.empty()) {
558*c9157d92SDimitry Andric     Register Reg = Worklist.pop_back_val();
559*c9157d92SDimitry Andric     for (MachineOperand &MO : MRI->use_operands(Reg)) {
560*c9157d92SDimitry Andric       MachineInstr *U = MO.getParent();
561*c9157d92SDimitry Andric       assert((U->isCopy() || U->isDebugInstr()) &&
562*c9157d92SDimitry Andric              "Only debug uses and copies must remain");
563*c9157d92SDimitry Andric       if (U->isCopy())
564*c9157d92SDimitry Andric         Worklist.push_back(U->getOperand(0).getReg());
565*c9157d92SDimitry Andric       Cleanup.push_back(&MO);
566*c9157d92SDimitry Andric     }
567*c9157d92SDimitry Andric   }
568*c9157d92SDimitry Andric 
569*c9157d92SDimitry Andric   // Delete the dead COPYs and clear operands in debug instructions
570*c9157d92SDimitry Andric   for (MachineOperand *MO : Cleanup) {
571*c9157d92SDimitry Andric     MachineInstr *I = MO->getParent();
572*c9157d92SDimitry Andric     if (I->isCopy()) {
573*c9157d92SDimitry Andric       I->eraseFromParent();
574*c9157d92SDimitry Andric     } else {
575*c9157d92SDimitry Andric       MO->setReg(0);
576*c9157d92SDimitry Andric       MO->setSubReg(0);
577*c9157d92SDimitry Andric     }
578*c9157d92SDimitry Andric   }
579*c9157d92SDimitry Andric 
580*c9157d92SDimitry Andric   MI.eraseFromParent();
581*c9157d92SDimitry Andric   return true;
582*c9157d92SDimitry Andric }
583*c9157d92SDimitry Andric 
5840b57cec5SDimitry Andric /// AllUsesDominatedByBlock - Return true if all uses of the specified register
5850b57cec5SDimitry Andric /// occur in blocks dominated by the specified block. If any use is in the
5860b57cec5SDimitry Andric /// definition block, then return false since it is never legal to move def
5870b57cec5SDimitry Andric /// after uses.
AllUsesDominatedByBlock(Register Reg,MachineBasicBlock * MBB,MachineBasicBlock * DefMBB,bool & BreakPHIEdge,bool & LocalUse) const588e8d8bef9SDimitry Andric bool MachineSinking::AllUsesDominatedByBlock(Register Reg,
5890b57cec5SDimitry Andric                                              MachineBasicBlock *MBB,
5900b57cec5SDimitry Andric                                              MachineBasicBlock *DefMBB,
5910b57cec5SDimitry Andric                                              bool &BreakPHIEdge,
5920b57cec5SDimitry Andric                                              bool &LocalUse) const {
593bdd1243dSDimitry Andric   assert(Reg.isVirtual() && "Only makes sense for vregs");
5940b57cec5SDimitry Andric 
5950b57cec5SDimitry Andric   // Ignore debug uses because debug info doesn't affect the code.
5960b57cec5SDimitry Andric   if (MRI->use_nodbg_empty(Reg))
5970b57cec5SDimitry Andric     return true;
5980b57cec5SDimitry Andric 
5990b57cec5SDimitry Andric   // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
6000b57cec5SDimitry Andric   // into and they are all PHI nodes. In this case, machine-sink must break
6010b57cec5SDimitry Andric   // the critical edge first. e.g.
6020b57cec5SDimitry Andric   //
603d65cd7a5SDimitry Andric   // %bb.1:
6040b57cec5SDimitry Andric   //   Predecessors according to CFG: %bb.0
6050b57cec5SDimitry Andric   //     ...
606d65cd7a5SDimitry Andric   //     %def = DEC64_32r %x, implicit-def dead %eflags
6070b57cec5SDimitry Andric   //     ...
6080b57cec5SDimitry Andric   //     JE_4 <%bb.37>, implicit %eflags
6090b57cec5SDimitry Andric   //   Successors according to CFG: %bb.37 %bb.2
6100b57cec5SDimitry Andric   //
611d65cd7a5SDimitry Andric   // %bb.2:
612d65cd7a5SDimitry Andric   //     %p = PHI %y, %bb.0, %def, %bb.1
6135ffd83dbSDimitry Andric   if (all_of(MRI->use_nodbg_operands(Reg), [&](MachineOperand &MO) {
6140b57cec5SDimitry Andric         MachineInstr *UseInst = MO.getParent();
615fe013be4SDimitry Andric         unsigned OpNo = MO.getOperandNo();
6160b57cec5SDimitry Andric         MachineBasicBlock *UseBlock = UseInst->getParent();
617d65cd7a5SDimitry Andric         return UseBlock == MBB && UseInst->isPHI() &&
618d65cd7a5SDimitry Andric                UseInst->getOperand(OpNo + 1).getMBB() == DefMBB;
619d65cd7a5SDimitry Andric       })) {
620d65cd7a5SDimitry Andric     BreakPHIEdge = true;
6210b57cec5SDimitry Andric     return true;
622d65cd7a5SDimitry Andric   }
6230b57cec5SDimitry Andric 
6240b57cec5SDimitry Andric   for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
6250b57cec5SDimitry Andric     // Determine the block of the use.
6260b57cec5SDimitry Andric     MachineInstr *UseInst = MO.getParent();
6270b57cec5SDimitry Andric     unsigned OpNo = &MO - &UseInst->getOperand(0);
6280b57cec5SDimitry Andric     MachineBasicBlock *UseBlock = UseInst->getParent();
6290b57cec5SDimitry Andric     if (UseInst->isPHI()) {
6300b57cec5SDimitry Andric       // PHI nodes use the operand in the predecessor block, not the block with
6310b57cec5SDimitry Andric       // the PHI.
6320b57cec5SDimitry Andric       UseBlock = UseInst->getOperand(OpNo+1).getMBB();
6330b57cec5SDimitry Andric     } else if (UseBlock == DefMBB) {
6340b57cec5SDimitry Andric       LocalUse = true;
6350b57cec5SDimitry Andric       return false;
6360b57cec5SDimitry Andric     }
6370b57cec5SDimitry Andric 
6380b57cec5SDimitry Andric     // Check that it dominates.
6390b57cec5SDimitry Andric     if (!DT->dominates(MBB, UseBlock))
6400b57cec5SDimitry Andric       return false;
6410b57cec5SDimitry Andric   }
6420b57cec5SDimitry Andric 
6430b57cec5SDimitry Andric   return true;
6440b57cec5SDimitry Andric }
6450b57cec5SDimitry Andric 
646fe6060f1SDimitry Andric /// Return true if this machine instruction loads from global offset table or
647fe6060f1SDimitry Andric /// constant pool.
mayLoadFromGOTOrConstantPool(MachineInstr & MI)648fe6060f1SDimitry Andric static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
649fe6060f1SDimitry Andric   assert(MI.mayLoad() && "Expected MI that loads!");
650fe6060f1SDimitry Andric 
651fe6060f1SDimitry Andric   // If we lost memory operands, conservatively assume that the instruction
652fe6060f1SDimitry Andric   // reads from everything..
653fe6060f1SDimitry Andric   if (MI.memoperands_empty())
654fe6060f1SDimitry Andric     return true;
655fe6060f1SDimitry Andric 
656fe6060f1SDimitry Andric   for (MachineMemOperand *MemOp : MI.memoperands())
657fe6060f1SDimitry Andric     if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
658fe6060f1SDimitry Andric       if (PSV->isGOT() || PSV->isConstantPool())
659fe6060f1SDimitry Andric         return true;
660fe6060f1SDimitry Andric 
661fe6060f1SDimitry Andric   return false;
662fe6060f1SDimitry Andric }
663fe6060f1SDimitry Andric 
FindCycleSinkCandidates(MachineCycle * Cycle,MachineBasicBlock * BB,SmallVectorImpl<MachineInstr * > & Candidates)66481ad6265SDimitry Andric void MachineSinking::FindCycleSinkCandidates(
66581ad6265SDimitry Andric     MachineCycle *Cycle, MachineBasicBlock *BB,
666fe6060f1SDimitry Andric     SmallVectorImpl<MachineInstr *> &Candidates) {
667fe6060f1SDimitry Andric   for (auto &MI : *BB) {
66881ad6265SDimitry Andric     LLVM_DEBUG(dbgs() << "CycleSink: Analysing candidate: " << MI);
669fe6060f1SDimitry Andric     if (!TII->shouldSink(MI)) {
67081ad6265SDimitry Andric       LLVM_DEBUG(dbgs() << "CycleSink: Instruction not a candidate for this "
671fe6060f1SDimitry Andric                            "target\n");
672fe6060f1SDimitry Andric       continue;
673fe6060f1SDimitry Andric     }
67481ad6265SDimitry Andric     if (!isCycleInvariant(Cycle, MI)) {
67581ad6265SDimitry Andric       LLVM_DEBUG(dbgs() << "CycleSink: Instruction is not cycle invariant\n");
676fe6060f1SDimitry Andric       continue;
677fe6060f1SDimitry Andric     }
678fe6060f1SDimitry Andric     bool DontMoveAcrossStore = true;
679fe6060f1SDimitry Andric     if (!MI.isSafeToMove(AA, DontMoveAcrossStore)) {
68081ad6265SDimitry Andric       LLVM_DEBUG(dbgs() << "CycleSink: Instruction not safe to move.\n");
681fe6060f1SDimitry Andric       continue;
682fe6060f1SDimitry Andric     }
683fe6060f1SDimitry Andric     if (MI.mayLoad() && !mayLoadFromGOTOrConstantPool(MI)) {
68481ad6265SDimitry Andric       LLVM_DEBUG(dbgs() << "CycleSink: Dont sink GOT or constant pool loads\n");
685fe6060f1SDimitry Andric       continue;
686fe6060f1SDimitry Andric     }
687fe6060f1SDimitry Andric     if (MI.isConvergent())
688fe6060f1SDimitry Andric       continue;
689fe6060f1SDimitry Andric 
690fe6060f1SDimitry Andric     const MachineOperand &MO = MI.getOperand(0);
691fe6060f1SDimitry Andric     if (!MO.isReg() || !MO.getReg() || !MO.isDef())
692fe6060f1SDimitry Andric       continue;
693fe6060f1SDimitry Andric     if (!MRI->hasOneDef(MO.getReg()))
694fe6060f1SDimitry Andric       continue;
695fe6060f1SDimitry Andric 
69681ad6265SDimitry Andric     LLVM_DEBUG(dbgs() << "CycleSink: Instruction added as candidate.\n");
697fe6060f1SDimitry Andric     Candidates.push_back(&MI);
698fe6060f1SDimitry Andric   }
699fe6060f1SDimitry Andric }
700fe6060f1SDimitry Andric 
runOnMachineFunction(MachineFunction & MF)7010b57cec5SDimitry Andric bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
7020b57cec5SDimitry Andric   if (skipFunction(MF.getFunction()))
7030b57cec5SDimitry Andric     return false;
7040b57cec5SDimitry Andric 
7050b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "******** Machine Sinking ********\n");
7060b57cec5SDimitry Andric 
707*c9157d92SDimitry Andric   STI = &MF.getSubtarget();
708*c9157d92SDimitry Andric   TII = STI->getInstrInfo();
709*c9157d92SDimitry Andric   TRI = STI->getRegisterInfo();
7100b57cec5SDimitry Andric   MRI = &MF.getRegInfo();
7110b57cec5SDimitry Andric   DT = &getAnalysis<MachineDominatorTree>();
7120b57cec5SDimitry Andric   PDT = &getAnalysis<MachinePostDominatorTree>();
71381ad6265SDimitry Andric   CI = &getAnalysis<MachineCycleInfoWrapperPass>().getCycleInfo();
7140b57cec5SDimitry Andric   MBFI = UseBlockFreqInfo ? &getAnalysis<MachineBlockFrequencyInfo>() : nullptr;
7150b57cec5SDimitry Andric   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
7160b57cec5SDimitry Andric   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
717e8d8bef9SDimitry Andric   RegClassInfo.runOnMachineFunction(MF);
718*c9157d92SDimitry Andric   TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
719*c9157d92SDimitry Andric   EnableSinkAndFold = PassConfig->getEnableSinkAndFold();
7200b57cec5SDimitry Andric 
7210b57cec5SDimitry Andric   bool EverMadeChange = false;
7220b57cec5SDimitry Andric 
7230b57cec5SDimitry Andric   while (true) {
7240b57cec5SDimitry Andric     bool MadeChange = false;
7250b57cec5SDimitry Andric 
7260b57cec5SDimitry Andric     // Process all basic blocks.
7270b57cec5SDimitry Andric     CEBCandidates.clear();
7280b57cec5SDimitry Andric     ToSplit.clear();
7290b57cec5SDimitry Andric     for (auto &MBB: MF)
7300b57cec5SDimitry Andric       MadeChange |= ProcessBlock(MBB);
7310b57cec5SDimitry Andric 
7320b57cec5SDimitry Andric     // If we have anything we marked as toSplit, split it now.
733fcaf7f86SDimitry Andric     for (const auto &Pair : ToSplit) {
7340b57cec5SDimitry Andric       auto NewSucc = Pair.first->SplitCriticalEdge(Pair.second, *this);
7350b57cec5SDimitry Andric       if (NewSucc != nullptr) {
7360b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << " *** Splitting critical edge: "
7370b57cec5SDimitry Andric                           << printMBBReference(*Pair.first) << " -- "
7380b57cec5SDimitry Andric                           << printMBBReference(*NewSucc) << " -- "
7390b57cec5SDimitry Andric                           << printMBBReference(*Pair.second) << '\n');
740e8d8bef9SDimitry Andric         if (MBFI)
741e8d8bef9SDimitry Andric           MBFI->onEdgeSplit(*Pair.first, *NewSucc, *MBPI);
742e8d8bef9SDimitry Andric 
7430b57cec5SDimitry Andric         MadeChange = true;
7440b57cec5SDimitry Andric         ++NumSplit;
745*c9157d92SDimitry Andric         CI->splitCriticalEdge(Pair.first, Pair.second, NewSucc);
7460b57cec5SDimitry Andric       } else
7470b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << " *** Not legal to break critical edge\n");
7480b57cec5SDimitry Andric     }
7490b57cec5SDimitry Andric     // If this iteration over the code changed anything, keep iterating.
7500b57cec5SDimitry Andric     if (!MadeChange) break;
7510b57cec5SDimitry Andric     EverMadeChange = true;
7520b57cec5SDimitry Andric   }
7530b57cec5SDimitry Andric 
75481ad6265SDimitry Andric   if (SinkInstsIntoCycle) {
75581ad6265SDimitry Andric     SmallVector<MachineCycle *, 8> Cycles(CI->toplevel_begin(),
75681ad6265SDimitry Andric                                           CI->toplevel_end());
75781ad6265SDimitry Andric     for (auto *Cycle : Cycles) {
75881ad6265SDimitry Andric       MachineBasicBlock *Preheader = Cycle->getCyclePreheader();
759fe6060f1SDimitry Andric       if (!Preheader) {
76081ad6265SDimitry Andric         LLVM_DEBUG(dbgs() << "CycleSink: Can't find preheader\n");
761fe6060f1SDimitry Andric         continue;
762fe6060f1SDimitry Andric       }
763fe6060f1SDimitry Andric       SmallVector<MachineInstr *, 8> Candidates;
76481ad6265SDimitry Andric       FindCycleSinkCandidates(Cycle, Preheader, Candidates);
765fe6060f1SDimitry Andric 
766fe6060f1SDimitry Andric       // Walk the candidates in reverse order so that we start with the use
767fe6060f1SDimitry Andric       // of a def-use chain, if there is any.
768fe6060f1SDimitry Andric       // TODO: Sort the candidates using a cost-model.
769fe6060f1SDimitry Andric       unsigned i = 0;
770349cc55cSDimitry Andric       for (MachineInstr *I : llvm::reverse(Candidates)) {
77181ad6265SDimitry Andric         if (i++ == SinkIntoCycleLimit) {
77281ad6265SDimitry Andric           LLVM_DEBUG(dbgs() << "CycleSink:   Limit reached of instructions to "
773fe6060f1SDimitry Andric                                "be analysed.");
774fe6060f1SDimitry Andric           break;
775fe6060f1SDimitry Andric         }
776fe6060f1SDimitry Andric 
77781ad6265SDimitry Andric         if (!SinkIntoCycle(Cycle, *I))
778fe6060f1SDimitry Andric           break;
779fe6060f1SDimitry Andric         EverMadeChange = true;
78081ad6265SDimitry Andric         ++NumCycleSunk;
781fe6060f1SDimitry Andric       }
782fe6060f1SDimitry Andric     }
783fe6060f1SDimitry Andric   }
784fe6060f1SDimitry Andric 
785e8d8bef9SDimitry Andric   HasStoreCache.clear();
786e8d8bef9SDimitry Andric   StoreInstrCache.clear();
787e8d8bef9SDimitry Andric 
7880b57cec5SDimitry Andric   // Now clear any kill flags for recorded registers.
7890b57cec5SDimitry Andric   for (auto I : RegsToClearKillFlags)
7900b57cec5SDimitry Andric     MRI->clearKillFlags(I);
7910b57cec5SDimitry Andric   RegsToClearKillFlags.clear();
7920b57cec5SDimitry Andric 
7930b57cec5SDimitry Andric   return EverMadeChange;
7940b57cec5SDimitry Andric }
7950b57cec5SDimitry Andric 
ProcessBlock(MachineBasicBlock & MBB)7960b57cec5SDimitry Andric bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
797*c9157d92SDimitry Andric   if ((!EnableSinkAndFold && MBB.succ_size() <= 1) || MBB.empty())
798*c9157d92SDimitry Andric     return false;
7990b57cec5SDimitry Andric 
8000b57cec5SDimitry Andric   // Don't bother sinking code out of unreachable blocks. In addition to being
8010b57cec5SDimitry Andric   // unprofitable, it can also lead to infinite looping, because in an
80281ad6265SDimitry Andric   // unreachable cycle there may be nowhere to stop.
8030b57cec5SDimitry Andric   if (!DT->isReachableFromEntry(&MBB)) return false;
8040b57cec5SDimitry Andric 
8050b57cec5SDimitry Andric   bool MadeChange = false;
8060b57cec5SDimitry Andric 
80781ad6265SDimitry Andric   // Cache all successors, sorted by frequency info and cycle depth.
8080b57cec5SDimitry Andric   AllSuccsCache AllSuccessors;
8090b57cec5SDimitry Andric 
8100b57cec5SDimitry Andric   // Walk the basic block bottom-up.  Remember if we saw a store.
8110b57cec5SDimitry Andric   MachineBasicBlock::iterator I = MBB.end();
8120b57cec5SDimitry Andric   --I;
8130b57cec5SDimitry Andric   bool ProcessedBegin, SawStore = false;
8140b57cec5SDimitry Andric   do {
8150b57cec5SDimitry Andric     MachineInstr &MI = *I;  // The instruction to sink.
8160b57cec5SDimitry Andric 
8170b57cec5SDimitry Andric     // Predecrement I (if it's not begin) so that it isn't invalidated by
8180b57cec5SDimitry Andric     // sinking.
8190b57cec5SDimitry Andric     ProcessedBegin = I == MBB.begin();
8200b57cec5SDimitry Andric     if (!ProcessedBegin)
8210b57cec5SDimitry Andric       --I;
8220b57cec5SDimitry Andric 
823fe6060f1SDimitry Andric     if (MI.isDebugOrPseudoInstr()) {
824480093f4SDimitry Andric       if (MI.isDebugValue())
825480093f4SDimitry Andric         ProcessDbgInst(MI);
8260b57cec5SDimitry Andric       continue;
827480093f4SDimitry Andric     }
8280b57cec5SDimitry Andric 
829*c9157d92SDimitry Andric     if (EnableSinkAndFold && PerformSinkAndFold(MI, &MBB)) {
830*c9157d92SDimitry Andric       MadeChange = true;
831*c9157d92SDimitry Andric       continue;
832*c9157d92SDimitry Andric     }
833*c9157d92SDimitry Andric 
834*c9157d92SDimitry Andric     // Can't sink anything out of a block that has less than two successors.
835*c9157d92SDimitry Andric     if (MBB.succ_size() <= 1)
836*c9157d92SDimitry Andric       continue;
837*c9157d92SDimitry Andric 
838*c9157d92SDimitry Andric     if (PerformTrivialForwardCoalescing(MI, &MBB)) {
8390b57cec5SDimitry Andric       MadeChange = true;
8400b57cec5SDimitry Andric       continue;
8410b57cec5SDimitry Andric     }
8420b57cec5SDimitry Andric 
8430b57cec5SDimitry Andric     if (SinkInstruction(MI, SawStore, AllSuccessors)) {
8440b57cec5SDimitry Andric       ++NumSunk;
8450b57cec5SDimitry Andric       MadeChange = true;
8460b57cec5SDimitry Andric     }
8470b57cec5SDimitry Andric 
8480b57cec5SDimitry Andric     // If we just processed the first instruction in the block, we're done.
8490b57cec5SDimitry Andric   } while (!ProcessedBegin);
8500b57cec5SDimitry Andric 
851480093f4SDimitry Andric   SeenDbgUsers.clear();
852480093f4SDimitry Andric   SeenDbgVars.clear();
853e8d8bef9SDimitry Andric   // recalculate the bb register pressure after sinking one BB.
854e8d8bef9SDimitry Andric   CachedRegisterPressure.clear();
8550b57cec5SDimitry Andric   return MadeChange;
8560b57cec5SDimitry Andric }
8570b57cec5SDimitry Andric 
ProcessDbgInst(MachineInstr & MI)858480093f4SDimitry Andric void MachineSinking::ProcessDbgInst(MachineInstr &MI) {
859480093f4SDimitry Andric   // When we see DBG_VALUEs for registers, record any vreg it reads, so that
860480093f4SDimitry Andric   // we know what to sink if the vreg def sinks.
861480093f4SDimitry Andric   assert(MI.isDebugValue() && "Expected DBG_VALUE for processing");
862480093f4SDimitry Andric 
863480093f4SDimitry Andric   DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
864480093f4SDimitry Andric                     MI.getDebugLoc()->getInlinedAt());
865e8d8bef9SDimitry Andric   bool SeenBefore = SeenDbgVars.contains(Var);
866480093f4SDimitry Andric 
867fe6060f1SDimitry Andric   for (MachineOperand &MO : MI.debug_operands()) {
868480093f4SDimitry Andric     if (MO.isReg() && MO.getReg().isVirtual())
869480093f4SDimitry Andric       SeenDbgUsers[MO.getReg()].push_back(SeenDbgUser(&MI, SeenBefore));
870fe6060f1SDimitry Andric   }
871480093f4SDimitry Andric 
872480093f4SDimitry Andric   // Record the variable for any DBG_VALUE, to avoid re-ordering any of them.
873480093f4SDimitry Andric   SeenDbgVars.insert(Var);
874480093f4SDimitry Andric }
875480093f4SDimitry Andric 
isWorthBreakingCriticalEdge(MachineInstr & MI,MachineBasicBlock * From,MachineBasicBlock * To)8760b57cec5SDimitry Andric bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr &MI,
8770b57cec5SDimitry Andric                                                  MachineBasicBlock *From,
8780b57cec5SDimitry Andric                                                  MachineBasicBlock *To) {
8790b57cec5SDimitry Andric   // FIXME: Need much better heuristics.
8800b57cec5SDimitry Andric 
8810b57cec5SDimitry Andric   // If the pass has already considered breaking this edge (during this pass
8820b57cec5SDimitry Andric   // through the function), then let's go ahead and break it. This means
8830b57cec5SDimitry Andric   // sinking multiple "cheap" instructions into the same block.
8840b57cec5SDimitry Andric   if (!CEBCandidates.insert(std::make_pair(From, To)).second)
8850b57cec5SDimitry Andric     return true;
8860b57cec5SDimitry Andric 
8870b57cec5SDimitry Andric   if (!MI.isCopy() && !TII->isAsCheapAsAMove(MI))
8880b57cec5SDimitry Andric     return true;
8890b57cec5SDimitry Andric 
8900b57cec5SDimitry Andric   if (From->isSuccessor(To) && MBPI->getEdgeProbability(From, To) <=
8910b57cec5SDimitry Andric       BranchProbability(SplitEdgeProbabilityThreshold, 100))
8920b57cec5SDimitry Andric     return true;
8930b57cec5SDimitry Andric 
8940b57cec5SDimitry Andric   // MI is cheap, we probably don't want to break the critical edge for it.
8950b57cec5SDimitry Andric   // However, if this would allow some definitions of its source operands
8960b57cec5SDimitry Andric   // to be sunk then it's probably worth it.
897fe013be4SDimitry Andric   for (const MachineOperand &MO : MI.all_uses()) {
8988bcb0991SDimitry Andric     Register Reg = MO.getReg();
8990b57cec5SDimitry Andric     if (Reg == 0)
9000b57cec5SDimitry Andric       continue;
9010b57cec5SDimitry Andric 
9020b57cec5SDimitry Andric     // We don't move live definitions of physical registers,
9030b57cec5SDimitry Andric     // so sinking their uses won't enable any opportunities.
904bdd1243dSDimitry Andric     if (Reg.isPhysical())
9050b57cec5SDimitry Andric       continue;
9060b57cec5SDimitry Andric 
9070b57cec5SDimitry Andric     // If this instruction is the only user of a virtual register,
9080b57cec5SDimitry Andric     // check if breaking the edge will enable sinking
9090b57cec5SDimitry Andric     // both this instruction and the defining instruction.
9100b57cec5SDimitry Andric     if (MRI->hasOneNonDBGUse(Reg)) {
9110b57cec5SDimitry Andric       // If the definition resides in same MBB,
9120b57cec5SDimitry Andric       // claim it's likely we can sink these together.
9130b57cec5SDimitry Andric       // If definition resides elsewhere, we aren't
9140b57cec5SDimitry Andric       // blocking it from being sunk so don't break the edge.
9150b57cec5SDimitry Andric       MachineInstr *DefMI = MRI->getVRegDef(Reg);
9160b57cec5SDimitry Andric       if (DefMI->getParent() == MI.getParent())
9170b57cec5SDimitry Andric         return true;
9180b57cec5SDimitry Andric     }
9190b57cec5SDimitry Andric   }
9200b57cec5SDimitry Andric 
9210b57cec5SDimitry Andric   return false;
9220b57cec5SDimitry Andric }
9230b57cec5SDimitry Andric 
PostponeSplitCriticalEdge(MachineInstr & MI,MachineBasicBlock * FromBB,MachineBasicBlock * ToBB,bool BreakPHIEdge)9240b57cec5SDimitry Andric bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr &MI,
9250b57cec5SDimitry Andric                                                MachineBasicBlock *FromBB,
9260b57cec5SDimitry Andric                                                MachineBasicBlock *ToBB,
9270b57cec5SDimitry Andric                                                bool BreakPHIEdge) {
9280b57cec5SDimitry Andric   if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
9290b57cec5SDimitry Andric     return false;
9300b57cec5SDimitry Andric 
93181ad6265SDimitry Andric   // Avoid breaking back edge. From == To means backedge for single BB cycle.
9320b57cec5SDimitry Andric   if (!SplitEdges || FromBB == ToBB)
9330b57cec5SDimitry Andric     return false;
9340b57cec5SDimitry Andric 
93581ad6265SDimitry Andric   MachineCycle *FromCycle = CI->getCycle(FromBB);
93681ad6265SDimitry Andric   MachineCycle *ToCycle = CI->getCycle(ToBB);
93781ad6265SDimitry Andric 
93881ad6265SDimitry Andric   // Check for backedges of more "complex" cycles.
93981ad6265SDimitry Andric   if (FromCycle == ToCycle && FromCycle &&
94081ad6265SDimitry Andric       (!FromCycle->isReducible() || FromCycle->getHeader() == ToBB))
9410b57cec5SDimitry Andric     return false;
9420b57cec5SDimitry Andric 
9430b57cec5SDimitry Andric   // It's not always legal to break critical edges and sink the computation
9440b57cec5SDimitry Andric   // to the edge.
9450b57cec5SDimitry Andric   //
9460b57cec5SDimitry Andric   // %bb.1:
9470b57cec5SDimitry Andric   // v1024
9480b57cec5SDimitry Andric   // Beq %bb.3
9490b57cec5SDimitry Andric   // <fallthrough>
9500b57cec5SDimitry Andric   // %bb.2:
9510b57cec5SDimitry Andric   // ... no uses of v1024
9520b57cec5SDimitry Andric   // <fallthrough>
9530b57cec5SDimitry Andric   // %bb.3:
9540b57cec5SDimitry Andric   // ...
9550b57cec5SDimitry Andric   //       = v1024
9560b57cec5SDimitry Andric   //
9570b57cec5SDimitry Andric   // If %bb.1 -> %bb.3 edge is broken and computation of v1024 is inserted:
9580b57cec5SDimitry Andric   //
9590b57cec5SDimitry Andric   // %bb.1:
9600b57cec5SDimitry Andric   // ...
9610b57cec5SDimitry Andric   // Bne %bb.2
9620b57cec5SDimitry Andric   // %bb.4:
9630b57cec5SDimitry Andric   // v1024 =
9640b57cec5SDimitry Andric   // B %bb.3
9650b57cec5SDimitry Andric   // %bb.2:
9660b57cec5SDimitry Andric   // ... no uses of v1024
9670b57cec5SDimitry Andric   // <fallthrough>
9680b57cec5SDimitry Andric   // %bb.3:
9690b57cec5SDimitry Andric   // ...
9700b57cec5SDimitry Andric   //       = v1024
9710b57cec5SDimitry Andric   //
9720b57cec5SDimitry Andric   // This is incorrect since v1024 is not computed along the %bb.1->%bb.2->%bb.3
9730b57cec5SDimitry Andric   // flow. We need to ensure the new basic block where the computation is
9740b57cec5SDimitry Andric   // sunk to dominates all the uses.
9750b57cec5SDimitry Andric   // It's only legal to break critical edge and sink the computation to the
9760b57cec5SDimitry Andric   // new block if all the predecessors of "To", except for "From", are
9770b57cec5SDimitry Andric   // not dominated by "From". Given SSA property, this means these
9780b57cec5SDimitry Andric   // predecessors are dominated by "To".
9790b57cec5SDimitry Andric   //
9800b57cec5SDimitry Andric   // There is no need to do this check if all the uses are PHI nodes. PHI
9810b57cec5SDimitry Andric   // sources are only defined on the specific predecessor edges.
9820b57cec5SDimitry Andric   if (!BreakPHIEdge) {
983349cc55cSDimitry Andric     for (MachineBasicBlock *Pred : ToBB->predecessors())
984349cc55cSDimitry Andric       if (Pred != FromBB && !DT->dominates(ToBB, Pred))
9850b57cec5SDimitry Andric         return false;
9860b57cec5SDimitry Andric   }
9870b57cec5SDimitry Andric 
9880b57cec5SDimitry Andric   ToSplit.insert(std::make_pair(FromBB, ToBB));
9890b57cec5SDimitry Andric 
9900b57cec5SDimitry Andric   return true;
9910b57cec5SDimitry Andric }
9920b57cec5SDimitry Andric 
993e8d8bef9SDimitry Andric std::vector<unsigned> &
getBBRegisterPressure(const MachineBasicBlock & MBB)994*c9157d92SDimitry Andric MachineSinking::getBBRegisterPressure(const MachineBasicBlock &MBB) {
995e8d8bef9SDimitry Andric   // Currently to save compiling time, MBB's register pressure will not change
996e8d8bef9SDimitry Andric   // in one ProcessBlock iteration because of CachedRegisterPressure. but MBB's
997e8d8bef9SDimitry Andric   // register pressure is changed after sinking any instructions into it.
998e8d8bef9SDimitry Andric   // FIXME: need a accurate and cheap register pressure estiminate model here.
999e8d8bef9SDimitry Andric   auto RP = CachedRegisterPressure.find(&MBB);
1000e8d8bef9SDimitry Andric   if (RP != CachedRegisterPressure.end())
1001e8d8bef9SDimitry Andric     return RP->second;
1002e8d8bef9SDimitry Andric 
1003e8d8bef9SDimitry Andric   RegionPressure Pressure;
1004e8d8bef9SDimitry Andric   RegPressureTracker RPTracker(Pressure);
1005e8d8bef9SDimitry Andric 
1006e8d8bef9SDimitry Andric   // Initialize the register pressure tracker.
1007e8d8bef9SDimitry Andric   RPTracker.init(MBB.getParent(), &RegClassInfo, nullptr, &MBB, MBB.end(),
1008e8d8bef9SDimitry Andric                  /*TrackLaneMasks*/ false, /*TrackUntiedDefs=*/true);
1009e8d8bef9SDimitry Andric 
1010*c9157d92SDimitry Andric   for (MachineBasicBlock::const_iterator MII = MBB.instr_end(),
1011e8d8bef9SDimitry Andric                                          MIE = MBB.instr_begin();
1012e8d8bef9SDimitry Andric        MII != MIE; --MII) {
1013*c9157d92SDimitry Andric     const MachineInstr &MI = *std::prev(MII);
1014fe6060f1SDimitry Andric     if (MI.isDebugInstr() || MI.isPseudoProbe())
1015e8d8bef9SDimitry Andric       continue;
1016e8d8bef9SDimitry Andric     RegisterOperands RegOpers;
1017e8d8bef9SDimitry Andric     RegOpers.collect(MI, *TRI, *MRI, false, false);
1018e8d8bef9SDimitry Andric     RPTracker.recedeSkipDebugValues();
1019e8d8bef9SDimitry Andric     assert(&*RPTracker.getPos() == &MI && "RPTracker sync error!");
1020e8d8bef9SDimitry Andric     RPTracker.recede(RegOpers);
1021e8d8bef9SDimitry Andric   }
1022e8d8bef9SDimitry Andric 
1023e8d8bef9SDimitry Andric   RPTracker.closeRegion();
1024e8d8bef9SDimitry Andric   auto It = CachedRegisterPressure.insert(
1025e8d8bef9SDimitry Andric       std::make_pair(&MBB, RPTracker.getPressure().MaxSetPressure));
1026e8d8bef9SDimitry Andric   return It.first->second;
1027e8d8bef9SDimitry Andric }
1028e8d8bef9SDimitry Andric 
registerPressureSetExceedsLimit(unsigned NRegs,const TargetRegisterClass * RC,const MachineBasicBlock & MBB)1029*c9157d92SDimitry Andric bool MachineSinking::registerPressureSetExceedsLimit(
1030*c9157d92SDimitry Andric     unsigned NRegs, const TargetRegisterClass *RC,
1031*c9157d92SDimitry Andric     const MachineBasicBlock &MBB) {
1032*c9157d92SDimitry Andric   unsigned Weight = NRegs * TRI->getRegClassWeight(RC).RegWeight;
1033*c9157d92SDimitry Andric   const int *PS = TRI->getRegClassPressureSets(RC);
1034*c9157d92SDimitry Andric   std::vector<unsigned> BBRegisterPressure = getBBRegisterPressure(MBB);
1035*c9157d92SDimitry Andric   for (; *PS != -1; PS++)
1036*c9157d92SDimitry Andric     if (Weight + BBRegisterPressure[*PS] >=
1037*c9157d92SDimitry Andric         TRI->getRegPressureSetLimit(*MBB.getParent(), *PS))
1038*c9157d92SDimitry Andric       return true;
1039*c9157d92SDimitry Andric   return false;
1040*c9157d92SDimitry Andric }
1041*c9157d92SDimitry Andric 
10420b57cec5SDimitry Andric /// isProfitableToSinkTo - Return true if it is profitable to sink MI.
isProfitableToSinkTo(Register Reg,MachineInstr & MI,MachineBasicBlock * MBB,MachineBasicBlock * SuccToSinkTo,AllSuccsCache & AllSuccessors)1043e8d8bef9SDimitry Andric bool MachineSinking::isProfitableToSinkTo(Register Reg, MachineInstr &MI,
10440b57cec5SDimitry Andric                                           MachineBasicBlock *MBB,
10450b57cec5SDimitry Andric                                           MachineBasicBlock *SuccToSinkTo,
10460b57cec5SDimitry Andric                                           AllSuccsCache &AllSuccessors) {
10470b57cec5SDimitry Andric   assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
10480b57cec5SDimitry Andric 
10490b57cec5SDimitry Andric   if (MBB == SuccToSinkTo)
10500b57cec5SDimitry Andric     return false;
10510b57cec5SDimitry Andric 
10520b57cec5SDimitry Andric   // It is profitable if SuccToSinkTo does not post dominate current block.
10530b57cec5SDimitry Andric   if (!PDT->dominates(SuccToSinkTo, MBB))
10540b57cec5SDimitry Andric     return true;
10550b57cec5SDimitry Andric 
105681ad6265SDimitry Andric   // It is profitable to sink an instruction from a deeper cycle to a shallower
105781ad6265SDimitry Andric   // cycle, even if the latter post-dominates the former (PR21115).
105881ad6265SDimitry Andric   if (CI->getCycleDepth(MBB) > CI->getCycleDepth(SuccToSinkTo))
10590b57cec5SDimitry Andric     return true;
10600b57cec5SDimitry Andric 
10610b57cec5SDimitry Andric   // Check if only use in post dominated block is PHI instruction.
10620b57cec5SDimitry Andric   bool NonPHIUse = false;
10630b57cec5SDimitry Andric   for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) {
10640b57cec5SDimitry Andric     MachineBasicBlock *UseBlock = UseInst.getParent();
10650b57cec5SDimitry Andric     if (UseBlock == SuccToSinkTo && !UseInst.isPHI())
10660b57cec5SDimitry Andric       NonPHIUse = true;
10670b57cec5SDimitry Andric   }
10680b57cec5SDimitry Andric   if (!NonPHIUse)
10690b57cec5SDimitry Andric     return true;
10700b57cec5SDimitry Andric 
10710b57cec5SDimitry Andric   // If SuccToSinkTo post dominates then also it may be profitable if MI
10720b57cec5SDimitry Andric   // can further profitably sinked into another block in next round.
10730b57cec5SDimitry Andric   bool BreakPHIEdge = false;
10740b57cec5SDimitry Andric   // FIXME - If finding successor is compile time expensive then cache results.
10750b57cec5SDimitry Andric   if (MachineBasicBlock *MBB2 =
10760b57cec5SDimitry Andric           FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge, AllSuccessors))
10770b57cec5SDimitry Andric     return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2, AllSuccessors);
10780b57cec5SDimitry Andric 
107981ad6265SDimitry Andric   MachineCycle *MCycle = CI->getCycle(MBB);
1080e8d8bef9SDimitry Andric 
108181ad6265SDimitry Andric   // If the instruction is not inside a cycle, it is not profitable to sink MI to
1082e8d8bef9SDimitry Andric   // a post dominate block SuccToSinkTo.
108381ad6265SDimitry Andric   if (!MCycle)
10840b57cec5SDimitry Andric     return false;
1085e8d8bef9SDimitry Andric 
108681ad6265SDimitry Andric   // If this instruction is inside a Cycle and sinking this instruction can make
1087e8d8bef9SDimitry Andric   // more registers live range shorten, it is still prifitable.
10884824e7fdSDimitry Andric   for (const MachineOperand &MO : MI.operands()) {
1089e8d8bef9SDimitry Andric     // Ignore non-register operands.
1090e8d8bef9SDimitry Andric     if (!MO.isReg())
1091e8d8bef9SDimitry Andric       continue;
1092e8d8bef9SDimitry Andric     Register Reg = MO.getReg();
1093e8d8bef9SDimitry Andric     if (Reg == 0)
1094e8d8bef9SDimitry Andric       continue;
1095e8d8bef9SDimitry Andric 
1096bdd1243dSDimitry Andric     if (Reg.isPhysical()) {
1097fe013be4SDimitry Andric       // Don't handle non-constant and non-ignorable physical register uses.
1098fe013be4SDimitry Andric       if (MO.isUse() && !MRI->isConstantPhysReg(Reg) && !TII->isIgnorableUse(MO))
1099e8d8bef9SDimitry Andric         return false;
1100fe013be4SDimitry Andric       continue;
110104eeddc0SDimitry Andric     }
1102e8d8bef9SDimitry Andric 
1103e8d8bef9SDimitry Andric     // Users for the defs are all dominated by SuccToSinkTo.
1104e8d8bef9SDimitry Andric     if (MO.isDef()) {
1105e8d8bef9SDimitry Andric       // This def register's live range is shortened after sinking.
1106e8d8bef9SDimitry Andric       bool LocalUse = false;
1107e8d8bef9SDimitry Andric       if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB, BreakPHIEdge,
1108e8d8bef9SDimitry Andric                                    LocalUse))
1109e8d8bef9SDimitry Andric         return false;
1110e8d8bef9SDimitry Andric     } else {
1111e8d8bef9SDimitry Andric       MachineInstr *DefMI = MRI->getVRegDef(Reg);
111281ad6265SDimitry Andric       if (!DefMI)
1113e8d8bef9SDimitry Andric         continue;
111481ad6265SDimitry Andric       MachineCycle *Cycle = CI->getCycle(DefMI->getParent());
111581ad6265SDimitry Andric       // DefMI is defined outside of cycle. There should be no live range
111681ad6265SDimitry Andric       // impact for this operand. Defination outside of cycle means:
111781ad6265SDimitry Andric       // 1: defination is outside of cycle.
111881ad6265SDimitry Andric       // 2: defination is in this cycle, but it is a PHI in the cycle header.
111981ad6265SDimitry Andric       if (Cycle != MCycle || (DefMI->isPHI() && Cycle && Cycle->isReducible() &&
112081ad6265SDimitry Andric                               Cycle->getHeader() == DefMI->getParent()))
112181ad6265SDimitry Andric         continue;
112281ad6265SDimitry Andric       // The DefMI is defined inside the cycle.
1123e8d8bef9SDimitry Andric       // If sinking this operand makes some register pressure set exceed limit,
1124e8d8bef9SDimitry Andric       // it is not profitable.
1125*c9157d92SDimitry Andric       if (registerPressureSetExceedsLimit(1, MRI->getRegClass(Reg),
1126*c9157d92SDimitry Andric                                           *SuccToSinkTo)) {
1127e8d8bef9SDimitry Andric         LLVM_DEBUG(dbgs() << "register pressure exceed limit, not profitable.");
1128e8d8bef9SDimitry Andric         return false;
1129e8d8bef9SDimitry Andric       }
1130e8d8bef9SDimitry Andric     }
1131e8d8bef9SDimitry Andric   }
1132e8d8bef9SDimitry Andric 
113381ad6265SDimitry Andric   // If MI is in cycle and all its operands are alive across the whole cycle or
113481ad6265SDimitry Andric   // if no operand sinking make register pressure set exceed limit, it is
1135e8d8bef9SDimitry Andric   // profitable to sink MI.
1136e8d8bef9SDimitry Andric   return true;
11370b57cec5SDimitry Andric }
11380b57cec5SDimitry Andric 
11390b57cec5SDimitry Andric /// Get the sorted sequence of successors for this MachineBasicBlock, possibly
11400b57cec5SDimitry Andric /// computing it if it was not already cached.
11410b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 4> &
GetAllSortedSuccessors(MachineInstr & MI,MachineBasicBlock * MBB,AllSuccsCache & AllSuccessors) const11420b57cec5SDimitry Andric MachineSinking::GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
11430b57cec5SDimitry Andric                                        AllSuccsCache &AllSuccessors) const {
11440b57cec5SDimitry Andric   // Do we have the sorted successors in cache ?
11450b57cec5SDimitry Andric   auto Succs = AllSuccessors.find(MBB);
11460b57cec5SDimitry Andric   if (Succs != AllSuccessors.end())
11470b57cec5SDimitry Andric     return Succs->second;
11480b57cec5SDimitry Andric 
1149e8d8bef9SDimitry Andric   SmallVector<MachineBasicBlock *, 4> AllSuccs(MBB->successors());
11500b57cec5SDimitry Andric 
11510b57cec5SDimitry Andric   // Handle cases where sinking can happen but where the sink point isn't a
11520b57cec5SDimitry Andric   // successor. For example:
11530b57cec5SDimitry Andric   //
11540b57cec5SDimitry Andric   //   x = computation
11550b57cec5SDimitry Andric   //   if () {} else {}
11560b57cec5SDimitry Andric   //   use x
11570b57cec5SDimitry Andric   //
11585ffd83dbSDimitry Andric   for (MachineDomTreeNode *DTChild : DT->getNode(MBB)->children()) {
11590b57cec5SDimitry Andric     // DomTree children of MBB that have MBB as immediate dominator are added.
11600b57cec5SDimitry Andric     if (DTChild->getIDom()->getBlock() == MI.getParent() &&
11610b57cec5SDimitry Andric         // Skip MBBs already added to the AllSuccs vector above.
11620b57cec5SDimitry Andric         !MBB->isSuccessor(DTChild->getBlock()))
11630b57cec5SDimitry Andric       AllSuccs.push_back(DTChild->getBlock());
11645ffd83dbSDimitry Andric   }
11650b57cec5SDimitry Andric 
116681ad6265SDimitry Andric   // Sort Successors according to their cycle depth or block frequency info.
11670b57cec5SDimitry Andric   llvm::stable_sort(
11680b57cec5SDimitry Andric       AllSuccs, [this](const MachineBasicBlock *L, const MachineBasicBlock *R) {
11690b57cec5SDimitry Andric         uint64_t LHSFreq = MBFI ? MBFI->getBlockFreq(L).getFrequency() : 0;
11700b57cec5SDimitry Andric         uint64_t RHSFreq = MBFI ? MBFI->getBlockFreq(R).getFrequency() : 0;
1171*c9157d92SDimitry Andric         bool HasBlockFreq = LHSFreq != 0 || RHSFreq != 0;
11720b57cec5SDimitry Andric         return HasBlockFreq ? LHSFreq < RHSFreq
117381ad6265SDimitry Andric                             : CI->getCycleDepth(L) < CI->getCycleDepth(R);
11740b57cec5SDimitry Andric       });
11750b57cec5SDimitry Andric 
11760b57cec5SDimitry Andric   auto it = AllSuccessors.insert(std::make_pair(MBB, AllSuccs));
11770b57cec5SDimitry Andric 
11780b57cec5SDimitry Andric   return it.first->second;
11790b57cec5SDimitry Andric }
11800b57cec5SDimitry Andric 
11810b57cec5SDimitry Andric /// FindSuccToSinkTo - Find a successor to sink this instruction to.
11820b57cec5SDimitry Andric MachineBasicBlock *
FindSuccToSinkTo(MachineInstr & MI,MachineBasicBlock * MBB,bool & BreakPHIEdge,AllSuccsCache & AllSuccessors)11830b57cec5SDimitry Andric MachineSinking::FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
11840b57cec5SDimitry Andric                                  bool &BreakPHIEdge,
11850b57cec5SDimitry Andric                                  AllSuccsCache &AllSuccessors) {
11860b57cec5SDimitry Andric   assert (MBB && "Invalid MachineBasicBlock!");
11870b57cec5SDimitry Andric 
118881ad6265SDimitry Andric   // loop over all the operands of the specified instruction.  If there is
11890b57cec5SDimitry Andric   // anything we can't handle, bail out.
11900b57cec5SDimitry Andric 
11910b57cec5SDimitry Andric   // SuccToSinkTo - This is the successor to sink this instruction to, once we
11920b57cec5SDimitry Andric   // decide.
11930b57cec5SDimitry Andric   MachineBasicBlock *SuccToSinkTo = nullptr;
11944824e7fdSDimitry Andric   for (const MachineOperand &MO : MI.operands()) {
11950b57cec5SDimitry Andric     if (!MO.isReg()) continue;  // Ignore non-register operands.
11960b57cec5SDimitry Andric 
11978bcb0991SDimitry Andric     Register Reg = MO.getReg();
11980b57cec5SDimitry Andric     if (Reg == 0) continue;
11990b57cec5SDimitry Andric 
1200bdd1243dSDimitry Andric     if (Reg.isPhysical()) {
12010b57cec5SDimitry Andric       if (MO.isUse()) {
12020b57cec5SDimitry Andric         // If the physreg has no defs anywhere, it's just an ambient register
12030b57cec5SDimitry Andric         // and we can freely move its uses. Alternatively, if it's allocatable,
12040b57cec5SDimitry Andric         // it could get allocated to something with a def during allocation.
120504eeddc0SDimitry Andric         if (!MRI->isConstantPhysReg(Reg) && !TII->isIgnorableUse(MO))
12060b57cec5SDimitry Andric           return nullptr;
12070b57cec5SDimitry Andric       } else if (!MO.isDead()) {
12080b57cec5SDimitry Andric         // A def that isn't dead. We can't move it.
12090b57cec5SDimitry Andric         return nullptr;
12100b57cec5SDimitry Andric       }
12110b57cec5SDimitry Andric     } else {
12120b57cec5SDimitry Andric       // Virtual register uses are always safe to sink.
12130b57cec5SDimitry Andric       if (MO.isUse()) continue;
12140b57cec5SDimitry Andric 
12150b57cec5SDimitry Andric       // If it's not safe to move defs of the register class, then abort.
12160b57cec5SDimitry Andric       if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
12170b57cec5SDimitry Andric         return nullptr;
12180b57cec5SDimitry Andric 
12190b57cec5SDimitry Andric       // Virtual register defs can only be sunk if all their uses are in blocks
12200b57cec5SDimitry Andric       // dominated by one of the successors.
12210b57cec5SDimitry Andric       if (SuccToSinkTo) {
12220b57cec5SDimitry Andric         // If a previous operand picked a block to sink to, then this operand
12230b57cec5SDimitry Andric         // must be sinkable to the same block.
12240b57cec5SDimitry Andric         bool LocalUse = false;
12250b57cec5SDimitry Andric         if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
12260b57cec5SDimitry Andric                                      BreakPHIEdge, LocalUse))
12270b57cec5SDimitry Andric           return nullptr;
12280b57cec5SDimitry Andric 
12290b57cec5SDimitry Andric         continue;
12300b57cec5SDimitry Andric       }
12310b57cec5SDimitry Andric 
12320b57cec5SDimitry Andric       // Otherwise, we should look at all the successors and decide which one
12330b57cec5SDimitry Andric       // we should sink to. If we have reliable block frequency information
12340b57cec5SDimitry Andric       // (frequency != 0) available, give successors with smaller frequencies
123581ad6265SDimitry Andric       // higher priority, otherwise prioritize smaller cycle depths.
12360b57cec5SDimitry Andric       for (MachineBasicBlock *SuccBlock :
12370b57cec5SDimitry Andric            GetAllSortedSuccessors(MI, MBB, AllSuccessors)) {
12380b57cec5SDimitry Andric         bool LocalUse = false;
12390b57cec5SDimitry Andric         if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
12400b57cec5SDimitry Andric                                     BreakPHIEdge, LocalUse)) {
12410b57cec5SDimitry Andric           SuccToSinkTo = SuccBlock;
12420b57cec5SDimitry Andric           break;
12430b57cec5SDimitry Andric         }
12440b57cec5SDimitry Andric         if (LocalUse)
12450b57cec5SDimitry Andric           // Def is used locally, it's never safe to move this def.
12460b57cec5SDimitry Andric           return nullptr;
12470b57cec5SDimitry Andric       }
12480b57cec5SDimitry Andric 
12490b57cec5SDimitry Andric       // If we couldn't find a block to sink to, ignore this instruction.
12500b57cec5SDimitry Andric       if (!SuccToSinkTo)
12510b57cec5SDimitry Andric         return nullptr;
12520b57cec5SDimitry Andric       if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo, AllSuccessors))
12530b57cec5SDimitry Andric         return nullptr;
12540b57cec5SDimitry Andric     }
12550b57cec5SDimitry Andric   }
12560b57cec5SDimitry Andric 
12570b57cec5SDimitry Andric   // It is not possible to sink an instruction into its own block.  This can
125881ad6265SDimitry Andric   // happen with cycles.
12590b57cec5SDimitry Andric   if (MBB == SuccToSinkTo)
12600b57cec5SDimitry Andric     return nullptr;
12610b57cec5SDimitry Andric 
12620b57cec5SDimitry Andric   // It's not safe to sink instructions to EH landing pad. Control flow into
12630b57cec5SDimitry Andric   // landing pad is implicitly defined.
1264*c9157d92SDimitry Andric   if (SuccToSinkTo && SuccToSinkTo->isEHPad())
12650b57cec5SDimitry Andric     return nullptr;
12660b57cec5SDimitry Andric 
12675ffd83dbSDimitry Andric   // It ought to be okay to sink instructions into an INLINEASM_BR target, but
12685ffd83dbSDimitry Andric   // only if we make sure that MI occurs _before_ an INLINEASM_BR instruction in
12695ffd83dbSDimitry Andric   // the source block (which this code does not yet do). So for now, forbid
12705ffd83dbSDimitry Andric   // doing so.
1271*c9157d92SDimitry Andric   if (SuccToSinkTo && SuccToSinkTo->isInlineAsmBrIndirectTarget())
1272fe013be4SDimitry Andric     return nullptr;
1273fe013be4SDimitry Andric 
1274*c9157d92SDimitry Andric   if (SuccToSinkTo && !TII->isSafeToSink(MI, SuccToSinkTo, CI))
12755ffd83dbSDimitry Andric     return nullptr;
12765ffd83dbSDimitry Andric 
12770b57cec5SDimitry Andric   return SuccToSinkTo;
12780b57cec5SDimitry Andric }
12790b57cec5SDimitry Andric 
12800b57cec5SDimitry Andric /// Return true if MI is likely to be usable as a memory operation by the
12810b57cec5SDimitry Andric /// implicit null check optimization.
12820b57cec5SDimitry Andric ///
12830b57cec5SDimitry Andric /// This is a "best effort" heuristic, and should not be relied upon for
12840b57cec5SDimitry Andric /// correctness.  This returning true does not guarantee that the implicit null
12850b57cec5SDimitry Andric /// check optimization is legal over MI, and this returning false does not
12860b57cec5SDimitry Andric /// guarantee MI cannot possibly be used to do a null check.
SinkingPreventsImplicitNullCheck(MachineInstr & MI,const TargetInstrInfo * TII,const TargetRegisterInfo * TRI)12870b57cec5SDimitry Andric static bool SinkingPreventsImplicitNullCheck(MachineInstr &MI,
12880b57cec5SDimitry Andric                                              const TargetInstrInfo *TII,
12890b57cec5SDimitry Andric                                              const TargetRegisterInfo *TRI) {
12900b57cec5SDimitry Andric   using MachineBranchPredicate = TargetInstrInfo::MachineBranchPredicate;
12910b57cec5SDimitry Andric 
12920b57cec5SDimitry Andric   auto *MBB = MI.getParent();
12930b57cec5SDimitry Andric   if (MBB->pred_size() != 1)
12940b57cec5SDimitry Andric     return false;
12950b57cec5SDimitry Andric 
12960b57cec5SDimitry Andric   auto *PredMBB = *MBB->pred_begin();
12970b57cec5SDimitry Andric   auto *PredBB = PredMBB->getBasicBlock();
12980b57cec5SDimitry Andric 
12990b57cec5SDimitry Andric   // Frontends that don't use implicit null checks have no reason to emit
13000b57cec5SDimitry Andric   // branches with make.implicit metadata, and this function should always
13010b57cec5SDimitry Andric   // return false for them.
13020b57cec5SDimitry Andric   if (!PredBB ||
13030b57cec5SDimitry Andric       !PredBB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit))
13040b57cec5SDimitry Andric     return false;
13050b57cec5SDimitry Andric 
13060b57cec5SDimitry Andric   const MachineOperand *BaseOp;
13070b57cec5SDimitry Andric   int64_t Offset;
13085ffd83dbSDimitry Andric   bool OffsetIsScalable;
13095ffd83dbSDimitry Andric   if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI))
13100b57cec5SDimitry Andric     return false;
13110b57cec5SDimitry Andric 
13120b57cec5SDimitry Andric   if (!BaseOp->isReg())
13130b57cec5SDimitry Andric     return false;
13140b57cec5SDimitry Andric 
13150b57cec5SDimitry Andric   if (!(MI.mayLoad() && !MI.isPredicable()))
13160b57cec5SDimitry Andric     return false;
13170b57cec5SDimitry Andric 
13180b57cec5SDimitry Andric   MachineBranchPredicate MBP;
13190b57cec5SDimitry Andric   if (TII->analyzeBranchPredicate(*PredMBB, MBP, false))
13200b57cec5SDimitry Andric     return false;
13210b57cec5SDimitry Andric 
13220b57cec5SDimitry Andric   return MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
13230b57cec5SDimitry Andric          (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
13240b57cec5SDimitry Andric           MBP.Predicate == MachineBranchPredicate::PRED_EQ) &&
13250b57cec5SDimitry Andric          MBP.LHS.getReg() == BaseOp->getReg();
13260b57cec5SDimitry Andric }
13270b57cec5SDimitry Andric 
1328480093f4SDimitry Andric /// If the sunk instruction is a copy, try to forward the copy instead of
1329480093f4SDimitry Andric /// leaving an 'undef' DBG_VALUE in the original location. Don't do this if
1330480093f4SDimitry Andric /// there's any subregister weirdness involved. Returns true if copy
1331480093f4SDimitry Andric /// propagation occurred.
attemptDebugCopyProp(MachineInstr & SinkInst,MachineInstr & DbgMI,Register Reg)1332fe6060f1SDimitry Andric static bool attemptDebugCopyProp(MachineInstr &SinkInst, MachineInstr &DbgMI,
1333fe6060f1SDimitry Andric                                  Register Reg) {
1334480093f4SDimitry Andric   const MachineRegisterInfo &MRI = SinkInst.getMF()->getRegInfo();
1335480093f4SDimitry Andric   const TargetInstrInfo &TII = *SinkInst.getMF()->getSubtarget().getInstrInfo();
1336480093f4SDimitry Andric 
1337480093f4SDimitry Andric   // Copy DBG_VALUE operand and set the original to undef. We then check to
1338480093f4SDimitry Andric   // see whether this is something that can be copy-forwarded. If it isn't,
1339480093f4SDimitry Andric   // continue around the loop.
1340480093f4SDimitry Andric 
1341480093f4SDimitry Andric   const MachineOperand *SrcMO = nullptr, *DstMO = nullptr;
1342480093f4SDimitry Andric   auto CopyOperands = TII.isCopyInstr(SinkInst);
1343480093f4SDimitry Andric   if (!CopyOperands)
1344480093f4SDimitry Andric     return false;
1345480093f4SDimitry Andric   SrcMO = CopyOperands->Source;
1346480093f4SDimitry Andric   DstMO = CopyOperands->Destination;
1347480093f4SDimitry Andric 
1348480093f4SDimitry Andric   // Check validity of forwarding this copy.
1349480093f4SDimitry Andric   bool PostRA = MRI.getNumVirtRegs() == 0;
1350480093f4SDimitry Andric 
1351480093f4SDimitry Andric   // Trying to forward between physical and virtual registers is too hard.
1352fe6060f1SDimitry Andric   if (Reg.isVirtual() != SrcMO->getReg().isVirtual())
1353480093f4SDimitry Andric     return false;
1354480093f4SDimitry Andric 
1355480093f4SDimitry Andric   // Only try virtual register copy-forwarding before regalloc, and physical
1356480093f4SDimitry Andric   // register copy-forwarding after regalloc.
1357fe6060f1SDimitry Andric   bool arePhysRegs = !Reg.isVirtual();
1358480093f4SDimitry Andric   if (arePhysRegs != PostRA)
1359480093f4SDimitry Andric     return false;
1360480093f4SDimitry Andric 
1361480093f4SDimitry Andric   // Pre-regalloc, only forward if all subregisters agree (or there are no
1362480093f4SDimitry Andric   // subregs at all). More analysis might recover some forwardable copies.
1363fe6060f1SDimitry Andric   if (!PostRA)
1364fe6060f1SDimitry Andric     for (auto &DbgMO : DbgMI.getDebugOperandsForReg(Reg))
1365fe6060f1SDimitry Andric       if (DbgMO.getSubReg() != SrcMO->getSubReg() ||
1366fe6060f1SDimitry Andric           DbgMO.getSubReg() != DstMO->getSubReg())
1367480093f4SDimitry Andric         return false;
1368480093f4SDimitry Andric 
1369480093f4SDimitry Andric   // Post-regalloc, we may be sinking a DBG_VALUE of a sub or super-register
1370480093f4SDimitry Andric   // of this copy. Only forward the copy if the DBG_VALUE operand exactly
1371480093f4SDimitry Andric   // matches the copy destination.
1372fe6060f1SDimitry Andric   if (PostRA && Reg != DstMO->getReg())
1373480093f4SDimitry Andric     return false;
1374480093f4SDimitry Andric 
1375fe6060f1SDimitry Andric   for (auto &DbgMO : DbgMI.getDebugOperandsForReg(Reg)) {
13765ffd83dbSDimitry Andric     DbgMO.setReg(SrcMO->getReg());
13775ffd83dbSDimitry Andric     DbgMO.setSubReg(SrcMO->getSubReg());
1378fe6060f1SDimitry Andric   }
1379480093f4SDimitry Andric   return true;
1380480093f4SDimitry Andric }
1381480093f4SDimitry Andric 
1382fe6060f1SDimitry Andric using MIRegs = std::pair<MachineInstr *, SmallVector<unsigned, 2>>;
1383480093f4SDimitry Andric /// Sink an instruction and its associated debug instructions.
performSink(MachineInstr & MI,MachineBasicBlock & SuccToSinkTo,MachineBasicBlock::iterator InsertPos,ArrayRef<MIRegs> DbgValuesToSink)13840b57cec5SDimitry Andric static void performSink(MachineInstr &MI, MachineBasicBlock &SuccToSinkTo,
13850b57cec5SDimitry Andric                         MachineBasicBlock::iterator InsertPos,
138681ad6265SDimitry Andric                         ArrayRef<MIRegs> DbgValuesToSink) {
13870b57cec5SDimitry Andric   // If we cannot find a location to use (merge with), then we erase the debug
13880b57cec5SDimitry Andric   // location to prevent debug-info driven tools from potentially reporting
13890b57cec5SDimitry Andric   // wrong location information.
13900b57cec5SDimitry Andric   if (!SuccToSinkTo.empty() && InsertPos != SuccToSinkTo.end())
13910b57cec5SDimitry Andric     MI.setDebugLoc(DILocation::getMergedLocation(MI.getDebugLoc(),
13920b57cec5SDimitry Andric                                                  InsertPos->getDebugLoc()));
13930b57cec5SDimitry Andric   else
13940b57cec5SDimitry Andric     MI.setDebugLoc(DebugLoc());
13950b57cec5SDimitry Andric 
13960b57cec5SDimitry Andric   // Move the instruction.
13970b57cec5SDimitry Andric   MachineBasicBlock *ParentBlock = MI.getParent();
13980b57cec5SDimitry Andric   SuccToSinkTo.splice(InsertPos, ParentBlock, MI,
13990b57cec5SDimitry Andric                       ++MachineBasicBlock::iterator(MI));
14000b57cec5SDimitry Andric 
1401480093f4SDimitry Andric   // Sink a copy of debug users to the insert position. Mark the original
1402480093f4SDimitry Andric   // DBG_VALUE location as 'undef', indicating that any earlier variable
1403480093f4SDimitry Andric   // location should be terminated as we've optimised away the value at this
1404480093f4SDimitry Andric   // point.
140581ad6265SDimitry Andric   for (const auto &DbgValueToSink : DbgValuesToSink) {
1406fe6060f1SDimitry Andric     MachineInstr *DbgMI = DbgValueToSink.first;
1407fe6060f1SDimitry Andric     MachineInstr *NewDbgMI = DbgMI->getMF()->CloneMachineInstr(DbgMI);
1408480093f4SDimitry Andric     SuccToSinkTo.insert(InsertPos, NewDbgMI);
1409480093f4SDimitry Andric 
1410fe6060f1SDimitry Andric     bool PropagatedAllSunkOps = true;
1411fe6060f1SDimitry Andric     for (unsigned Reg : DbgValueToSink.second) {
1412fe6060f1SDimitry Andric       if (DbgMI->hasDebugOperandForReg(Reg)) {
1413fe6060f1SDimitry Andric         if (!attemptDebugCopyProp(MI, *DbgMI, Reg)) {
1414fe6060f1SDimitry Andric           PropagatedAllSunkOps = false;
1415fe6060f1SDimitry Andric           break;
1416fe6060f1SDimitry Andric         }
1417fe6060f1SDimitry Andric       }
1418fe6060f1SDimitry Andric     }
1419fe6060f1SDimitry Andric     if (!PropagatedAllSunkOps)
14205ffd83dbSDimitry Andric       DbgMI->setDebugValueUndef();
14210b57cec5SDimitry Andric   }
14220b57cec5SDimitry Andric }
14230b57cec5SDimitry Andric 
1424e8d8bef9SDimitry Andric /// hasStoreBetween - check if there is store betweeen straight line blocks From
1425e8d8bef9SDimitry Andric /// and To.
hasStoreBetween(MachineBasicBlock * From,MachineBasicBlock * To,MachineInstr & MI)1426e8d8bef9SDimitry Andric bool MachineSinking::hasStoreBetween(MachineBasicBlock *From,
1427e8d8bef9SDimitry Andric                                      MachineBasicBlock *To, MachineInstr &MI) {
1428e8d8bef9SDimitry Andric   // Make sure From and To are in straight line which means From dominates To
1429e8d8bef9SDimitry Andric   // and To post dominates From.
1430e8d8bef9SDimitry Andric   if (!DT->dominates(From, To) || !PDT->dominates(To, From))
1431e8d8bef9SDimitry Andric     return true;
1432e8d8bef9SDimitry Andric 
1433e8d8bef9SDimitry Andric   auto BlockPair = std::make_pair(From, To);
1434e8d8bef9SDimitry Andric 
1435e8d8bef9SDimitry Andric   // Does these two blocks pair be queried before and have a definite cached
1436e8d8bef9SDimitry Andric   // result?
1437*c9157d92SDimitry Andric   if (auto It = HasStoreCache.find(BlockPair); It != HasStoreCache.end())
1438*c9157d92SDimitry Andric     return It->second;
1439e8d8bef9SDimitry Andric 
1440*c9157d92SDimitry Andric   if (auto It = StoreInstrCache.find(BlockPair); It != StoreInstrCache.end())
1441*c9157d92SDimitry Andric     return llvm::any_of(It->second, [&](MachineInstr *I) {
1442e8d8bef9SDimitry Andric       return I->mayAlias(AA, MI, false);
1443e8d8bef9SDimitry Andric     });
1444e8d8bef9SDimitry Andric 
1445e8d8bef9SDimitry Andric   bool SawStore = false;
1446e8d8bef9SDimitry Andric   bool HasAliasedStore = false;
1447e8d8bef9SDimitry Andric   DenseSet<MachineBasicBlock *> HandledBlocks;
1448e8d8bef9SDimitry Andric   DenseSet<MachineBasicBlock *> HandledDomBlocks;
1449e8d8bef9SDimitry Andric   // Go through all reachable blocks from From.
1450e8d8bef9SDimitry Andric   for (MachineBasicBlock *BB : depth_first(From)) {
1451e8d8bef9SDimitry Andric     // We insert the instruction at the start of block To, so no need to worry
1452e8d8bef9SDimitry Andric     // about stores inside To.
1453e8d8bef9SDimitry Andric     // Store in block From should be already considered when just enter function
1454e8d8bef9SDimitry Andric     // SinkInstruction.
1455e8d8bef9SDimitry Andric     if (BB == To || BB == From)
1456e8d8bef9SDimitry Andric       continue;
1457e8d8bef9SDimitry Andric 
1458e8d8bef9SDimitry Andric     // We already handle this BB in previous iteration.
1459e8d8bef9SDimitry Andric     if (HandledBlocks.count(BB))
1460e8d8bef9SDimitry Andric       continue;
1461e8d8bef9SDimitry Andric 
1462e8d8bef9SDimitry Andric     HandledBlocks.insert(BB);
1463e8d8bef9SDimitry Andric     // To post dominates BB, it must be a path from block From.
1464e8d8bef9SDimitry Andric     if (PDT->dominates(To, BB)) {
1465e8d8bef9SDimitry Andric       if (!HandledDomBlocks.count(BB))
1466e8d8bef9SDimitry Andric         HandledDomBlocks.insert(BB);
1467e8d8bef9SDimitry Andric 
1468e8d8bef9SDimitry Andric       // If this BB is too big or the block number in straight line between From
1469e8d8bef9SDimitry Andric       // and To is too big, stop searching to save compiling time.
147081ad6265SDimitry Andric       if (BB->sizeWithoutDebugLargerThan(SinkLoadInstsPerBlockThreshold) ||
1471e8d8bef9SDimitry Andric           HandledDomBlocks.size() > SinkLoadBlocksThreshold) {
1472e8d8bef9SDimitry Andric         for (auto *DomBB : HandledDomBlocks) {
1473e8d8bef9SDimitry Andric           if (DomBB != BB && DT->dominates(DomBB, BB))
1474e8d8bef9SDimitry Andric             HasStoreCache[std::make_pair(DomBB, To)] = true;
1475e8d8bef9SDimitry Andric           else if(DomBB != BB && DT->dominates(BB, DomBB))
1476e8d8bef9SDimitry Andric             HasStoreCache[std::make_pair(From, DomBB)] = true;
1477e8d8bef9SDimitry Andric         }
1478e8d8bef9SDimitry Andric         HasStoreCache[BlockPair] = true;
1479e8d8bef9SDimitry Andric         return true;
1480e8d8bef9SDimitry Andric       }
1481e8d8bef9SDimitry Andric 
1482e8d8bef9SDimitry Andric       for (MachineInstr &I : *BB) {
1483e8d8bef9SDimitry Andric         // Treat as alias conservatively for a call or an ordered memory
1484e8d8bef9SDimitry Andric         // operation.
1485e8d8bef9SDimitry Andric         if (I.isCall() || I.hasOrderedMemoryRef()) {
1486e8d8bef9SDimitry Andric           for (auto *DomBB : HandledDomBlocks) {
1487e8d8bef9SDimitry Andric             if (DomBB != BB && DT->dominates(DomBB, BB))
1488e8d8bef9SDimitry Andric               HasStoreCache[std::make_pair(DomBB, To)] = true;
1489e8d8bef9SDimitry Andric             else if(DomBB != BB && DT->dominates(BB, DomBB))
1490e8d8bef9SDimitry Andric               HasStoreCache[std::make_pair(From, DomBB)] = true;
1491e8d8bef9SDimitry Andric           }
1492e8d8bef9SDimitry Andric           HasStoreCache[BlockPair] = true;
1493e8d8bef9SDimitry Andric           return true;
1494e8d8bef9SDimitry Andric         }
1495e8d8bef9SDimitry Andric 
1496e8d8bef9SDimitry Andric         if (I.mayStore()) {
1497e8d8bef9SDimitry Andric           SawStore = true;
1498e8d8bef9SDimitry Andric           // We still have chance to sink MI if all stores between are not
1499e8d8bef9SDimitry Andric           // aliased to MI.
1500e8d8bef9SDimitry Andric           // Cache all store instructions, so that we don't need to go through
1501e8d8bef9SDimitry Andric           // all From reachable blocks for next load instruction.
1502e8d8bef9SDimitry Andric           if (I.mayAlias(AA, MI, false))
1503e8d8bef9SDimitry Andric             HasAliasedStore = true;
1504e8d8bef9SDimitry Andric           StoreInstrCache[BlockPair].push_back(&I);
1505e8d8bef9SDimitry Andric         }
1506e8d8bef9SDimitry Andric       }
1507e8d8bef9SDimitry Andric     }
1508e8d8bef9SDimitry Andric   }
1509e8d8bef9SDimitry Andric   // If there is no store at all, cache the result.
1510e8d8bef9SDimitry Andric   if (!SawStore)
1511e8d8bef9SDimitry Andric     HasStoreCache[BlockPair] = false;
1512e8d8bef9SDimitry Andric   return HasAliasedStore;
1513e8d8bef9SDimitry Andric }
1514e8d8bef9SDimitry Andric 
151581ad6265SDimitry Andric /// Sink instructions into cycles if profitable. This especially tries to
151681ad6265SDimitry Andric /// prevent register spills caused by register pressure if there is little to no
151781ad6265SDimitry Andric /// overhead moving instructions into cycles.
SinkIntoCycle(MachineCycle * Cycle,MachineInstr & I)151881ad6265SDimitry Andric bool MachineSinking::SinkIntoCycle(MachineCycle *Cycle, MachineInstr &I) {
151981ad6265SDimitry Andric   LLVM_DEBUG(dbgs() << "CycleSink: Finding sink block for: " << I);
152081ad6265SDimitry Andric   MachineBasicBlock *Preheader = Cycle->getCyclePreheader();
152181ad6265SDimitry Andric   assert(Preheader && "Cycle sink needs a preheader block");
1522fe6060f1SDimitry Andric   MachineBasicBlock *SinkBlock = nullptr;
1523fe6060f1SDimitry Andric   bool CanSink = true;
1524fe6060f1SDimitry Andric   const MachineOperand &MO = I.getOperand(0);
1525fe6060f1SDimitry Andric 
1526fe6060f1SDimitry Andric   for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
152781ad6265SDimitry Andric     LLVM_DEBUG(dbgs() << "CycleSink:   Analysing use: " << MI);
152881ad6265SDimitry Andric     if (!Cycle->contains(MI.getParent())) {
152981ad6265SDimitry Andric       LLVM_DEBUG(dbgs() << "CycleSink:   Use not in cycle, can't sink.\n");
1530fe6060f1SDimitry Andric       CanSink = false;
1531fe6060f1SDimitry Andric       break;
1532fe6060f1SDimitry Andric     }
1533fe6060f1SDimitry Andric 
1534fe6060f1SDimitry Andric     // FIXME: Come up with a proper cost model that estimates whether sinking
153581ad6265SDimitry Andric     // the instruction (and thus possibly executing it on every cycle
1536fe6060f1SDimitry Andric     // iteration) is more expensive than a register.
1537fe6060f1SDimitry Andric     // For now assumes that copies are cheap and thus almost always worth it.
1538fe6060f1SDimitry Andric     if (!MI.isCopy()) {
153981ad6265SDimitry Andric       LLVM_DEBUG(dbgs() << "CycleSink:   Use is not a copy\n");
1540fe6060f1SDimitry Andric       CanSink = false;
1541fe6060f1SDimitry Andric       break;
1542fe6060f1SDimitry Andric     }
1543fe6060f1SDimitry Andric     if (!SinkBlock) {
1544fe6060f1SDimitry Andric       SinkBlock = MI.getParent();
154581ad6265SDimitry Andric       LLVM_DEBUG(dbgs() << "CycleSink:   Setting sink block to: "
1546fe6060f1SDimitry Andric                         << printMBBReference(*SinkBlock) << "\n");
1547fe6060f1SDimitry Andric       continue;
1548fe6060f1SDimitry Andric     }
1549fe6060f1SDimitry Andric     SinkBlock = DT->findNearestCommonDominator(SinkBlock, MI.getParent());
1550fe6060f1SDimitry Andric     if (!SinkBlock) {
155181ad6265SDimitry Andric       LLVM_DEBUG(dbgs() << "CycleSink:   Can't find nearest dominator\n");
1552fe6060f1SDimitry Andric       CanSink = false;
1553fe6060f1SDimitry Andric       break;
1554fe6060f1SDimitry Andric     }
155581ad6265SDimitry Andric     LLVM_DEBUG(dbgs() << "CycleSink:   Setting nearest common dom block: " <<
1556fe6060f1SDimitry Andric                printMBBReference(*SinkBlock) << "\n");
1557fe6060f1SDimitry Andric   }
1558fe6060f1SDimitry Andric 
1559fe6060f1SDimitry Andric   if (!CanSink) {
156081ad6265SDimitry Andric     LLVM_DEBUG(dbgs() << "CycleSink: Can't sink instruction.\n");
1561fe6060f1SDimitry Andric     return false;
1562fe6060f1SDimitry Andric   }
1563fe6060f1SDimitry Andric   if (!SinkBlock) {
156481ad6265SDimitry Andric     LLVM_DEBUG(dbgs() << "CycleSink: Not sinking, can't find sink block.\n");
1565fe6060f1SDimitry Andric     return false;
1566fe6060f1SDimitry Andric   }
1567fe6060f1SDimitry Andric   if (SinkBlock == Preheader) {
156881ad6265SDimitry Andric     LLVM_DEBUG(
156981ad6265SDimitry Andric         dbgs() << "CycleSink: Not sinking, sink block is the preheader\n");
1570fe6060f1SDimitry Andric     return false;
1571fe6060f1SDimitry Andric   }
157281ad6265SDimitry Andric   if (SinkBlock->sizeWithoutDebugLargerThan(SinkLoadInstsPerBlockThreshold)) {
157381ad6265SDimitry Andric     LLVM_DEBUG(
157481ad6265SDimitry Andric         dbgs() << "CycleSink: Not Sinking, block too large to analyse.\n");
1575fe6060f1SDimitry Andric     return false;
1576fe6060f1SDimitry Andric   }
1577fe6060f1SDimitry Andric 
157881ad6265SDimitry Andric   LLVM_DEBUG(dbgs() << "CycleSink: Sinking instruction!\n");
157981ad6265SDimitry Andric   SinkBlock->splice(SinkBlock->SkipPHIsAndLabels(SinkBlock->begin()), Preheader,
158081ad6265SDimitry Andric                     I);
158181ad6265SDimitry Andric 
158281ad6265SDimitry Andric   // Conservatively clear any kill flags on uses of sunk instruction
158381ad6265SDimitry Andric   for (MachineOperand &MO : I.operands()) {
158481ad6265SDimitry Andric     if (MO.isReg() && MO.readsReg())
158581ad6265SDimitry Andric       RegsToClearKillFlags.insert(MO.getReg());
158681ad6265SDimitry Andric   }
1587fe6060f1SDimitry Andric 
1588fe6060f1SDimitry Andric   // The instruction is moved from its basic block, so do not retain the
1589fe6060f1SDimitry Andric   // debug information.
1590fe6060f1SDimitry Andric   assert(!I.isDebugInstr() && "Should not sink debug inst");
1591fe6060f1SDimitry Andric   I.setDebugLoc(DebugLoc());
1592fe6060f1SDimitry Andric   return true;
1593fe6060f1SDimitry Andric }
1594fe6060f1SDimitry Andric 
15950b57cec5SDimitry Andric /// SinkInstruction - Determine whether it is safe to sink the specified machine
15960b57cec5SDimitry Andric /// instruction out of its current block into a successor.
SinkInstruction(MachineInstr & MI,bool & SawStore,AllSuccsCache & AllSuccessors)15970b57cec5SDimitry Andric bool MachineSinking::SinkInstruction(MachineInstr &MI, bool &SawStore,
15980b57cec5SDimitry Andric                                      AllSuccsCache &AllSuccessors) {
15990b57cec5SDimitry Andric   // Don't sink instructions that the target prefers not to sink.
16000b57cec5SDimitry Andric   if (!TII->shouldSink(MI))
16010b57cec5SDimitry Andric     return false;
16020b57cec5SDimitry Andric 
16030b57cec5SDimitry Andric   // Check if it's safe to move the instruction.
16040b57cec5SDimitry Andric   if (!MI.isSafeToMove(AA, SawStore))
16050b57cec5SDimitry Andric     return false;
16060b57cec5SDimitry Andric 
16070b57cec5SDimitry Andric   // Convergent operations may not be made control-dependent on additional
16080b57cec5SDimitry Andric   // values.
16090b57cec5SDimitry Andric   if (MI.isConvergent())
16100b57cec5SDimitry Andric     return false;
16110b57cec5SDimitry Andric 
16120b57cec5SDimitry Andric   // Don't break implicit null checks.  This is a performance heuristic, and not
16130b57cec5SDimitry Andric   // required for correctness.
16140b57cec5SDimitry Andric   if (SinkingPreventsImplicitNullCheck(MI, TII, TRI))
16150b57cec5SDimitry Andric     return false;
16160b57cec5SDimitry Andric 
16170b57cec5SDimitry Andric   // FIXME: This should include support for sinking instructions within the
16180b57cec5SDimitry Andric   // block they are currently in to shorten the live ranges.  We often get
16190b57cec5SDimitry Andric   // instructions sunk into the top of a large block, but it would be better to
16200b57cec5SDimitry Andric   // also sink them down before their first use in the block.  This xform has to
16210b57cec5SDimitry Andric   // be careful not to *increase* register pressure though, e.g. sinking
16220b57cec5SDimitry Andric   // "x = y + z" down if it kills y and z would increase the live ranges of y
16230b57cec5SDimitry Andric   // and z and only shrink the live range of x.
16240b57cec5SDimitry Andric 
16250b57cec5SDimitry Andric   bool BreakPHIEdge = false;
16260b57cec5SDimitry Andric   MachineBasicBlock *ParentBlock = MI.getParent();
16270b57cec5SDimitry Andric   MachineBasicBlock *SuccToSinkTo =
16280b57cec5SDimitry Andric       FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge, AllSuccessors);
16290b57cec5SDimitry Andric 
16300b57cec5SDimitry Andric   // If there are no outputs, it must have side-effects.
16310b57cec5SDimitry Andric   if (!SuccToSinkTo)
16320b57cec5SDimitry Andric     return false;
16330b57cec5SDimitry Andric 
16340b57cec5SDimitry Andric   // If the instruction to move defines a dead physical register which is live
16350b57cec5SDimitry Andric   // when leaving the basic block, don't move it because it could turn into a
1636*c9157d92SDimitry Andric   // "zombie" define of that preg. E.g., EFLAGS.
1637fe013be4SDimitry Andric   for (const MachineOperand &MO : MI.all_defs()) {
16388bcb0991SDimitry Andric     Register Reg = MO.getReg();
1639bdd1243dSDimitry Andric     if (Reg == 0 || !Reg.isPhysical())
16408bcb0991SDimitry Andric       continue;
16410b57cec5SDimitry Andric     if (SuccToSinkTo->isLiveIn(Reg))
16420b57cec5SDimitry Andric       return false;
16430b57cec5SDimitry Andric   }
16440b57cec5SDimitry Andric 
16450b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccToSinkTo);
16460b57cec5SDimitry Andric 
16470b57cec5SDimitry Andric   // If the block has multiple predecessors, this is a critical edge.
16480b57cec5SDimitry Andric   // Decide if we can sink along it or need to break the edge.
16490b57cec5SDimitry Andric   if (SuccToSinkTo->pred_size() > 1) {
16500b57cec5SDimitry Andric     // We cannot sink a load across a critical edge - there may be stores in
16510b57cec5SDimitry Andric     // other code paths.
16520b57cec5SDimitry Andric     bool TryBreak = false;
1653e8d8bef9SDimitry Andric     bool Store =
1654e8d8bef9SDimitry Andric         MI.mayLoad() ? hasStoreBetween(ParentBlock, SuccToSinkTo, MI) : true;
1655e8d8bef9SDimitry Andric     if (!MI.isSafeToMove(AA, Store)) {
16560b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
16570b57cec5SDimitry Andric       TryBreak = true;
16580b57cec5SDimitry Andric     }
16590b57cec5SDimitry Andric 
16600b57cec5SDimitry Andric     // We don't want to sink across a critical edge if we don't dominate the
16610b57cec5SDimitry Andric     // successor. We could be introducing calculations to new code paths.
16620b57cec5SDimitry Andric     if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
16630b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
16640b57cec5SDimitry Andric       TryBreak = true;
16650b57cec5SDimitry Andric     }
16660b57cec5SDimitry Andric 
166781ad6265SDimitry Andric     // Don't sink instructions into a cycle.
166881ad6265SDimitry Andric     if (!TryBreak && CI->getCycle(SuccToSinkTo) &&
166981ad6265SDimitry Andric         (!CI->getCycle(SuccToSinkTo)->isReducible() ||
167081ad6265SDimitry Andric          CI->getCycle(SuccToSinkTo)->getHeader() == SuccToSinkTo)) {
167181ad6265SDimitry Andric       LLVM_DEBUG(dbgs() << " *** NOTE: cycle header found\n");
16720b57cec5SDimitry Andric       TryBreak = true;
16730b57cec5SDimitry Andric     }
16740b57cec5SDimitry Andric 
16750b57cec5SDimitry Andric     // Otherwise we are OK with sinking along a critical edge.
16760b57cec5SDimitry Andric     if (!TryBreak)
16770b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Sinking along critical edge.\n");
16780b57cec5SDimitry Andric     else {
16790b57cec5SDimitry Andric       // Mark this edge as to be split.
16800b57cec5SDimitry Andric       // If the edge can actually be split, the next iteration of the main loop
16810b57cec5SDimitry Andric       // will sink MI in the newly created block.
16820b57cec5SDimitry Andric       bool Status =
16830b57cec5SDimitry Andric         PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
16840b57cec5SDimitry Andric       if (!Status)
16850b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
16860b57cec5SDimitry Andric                              "break critical edge\n");
16870b57cec5SDimitry Andric       // The instruction will not be sunk this time.
16880b57cec5SDimitry Andric       return false;
16890b57cec5SDimitry Andric     }
16900b57cec5SDimitry Andric   }
16910b57cec5SDimitry Andric 
16920b57cec5SDimitry Andric   if (BreakPHIEdge) {
16930b57cec5SDimitry Andric     // BreakPHIEdge is true if all the uses are in the successor MBB being
16940b57cec5SDimitry Andric     // sunken into and they are all PHI nodes. In this case, machine-sink must
16950b57cec5SDimitry Andric     // break the critical edge first.
16960b57cec5SDimitry Andric     bool Status = PostponeSplitCriticalEdge(MI, ParentBlock,
16970b57cec5SDimitry Andric                                             SuccToSinkTo, BreakPHIEdge);
16980b57cec5SDimitry Andric     if (!Status)
16990b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
17000b57cec5SDimitry Andric                            "break critical edge\n");
17010b57cec5SDimitry Andric     // The instruction will not be sunk this time.
17020b57cec5SDimitry Andric     return false;
17030b57cec5SDimitry Andric   }
17040b57cec5SDimitry Andric 
17050b57cec5SDimitry Andric   // Determine where to insert into. Skip phi nodes.
170681ad6265SDimitry Andric   MachineBasicBlock::iterator InsertPos =
170781ad6265SDimitry Andric       SuccToSinkTo->SkipPHIsAndLabels(SuccToSinkTo->begin());
170881ad6265SDimitry Andric   if (blockPrologueInterferes(SuccToSinkTo, InsertPos, MI, TRI, TII, MRI)) {
170981ad6265SDimitry Andric     LLVM_DEBUG(dbgs() << " *** Not sinking: prologue interference\n");
171081ad6265SDimitry Andric     return false;
171181ad6265SDimitry Andric   }
17120b57cec5SDimitry Andric 
1713480093f4SDimitry Andric   // Collect debug users of any vreg that this inst defines.
1714fe6060f1SDimitry Andric   SmallVector<MIRegs, 4> DbgUsersToSink;
1715fe013be4SDimitry Andric   for (auto &MO : MI.all_defs()) {
1716fe013be4SDimitry Andric     if (!MO.getReg().isVirtual())
1717480093f4SDimitry Andric       continue;
1718480093f4SDimitry Andric     if (!SeenDbgUsers.count(MO.getReg()))
1719480093f4SDimitry Andric       continue;
1720480093f4SDimitry Andric 
1721480093f4SDimitry Andric     // Sink any users that don't pass any other DBG_VALUEs for this variable.
1722480093f4SDimitry Andric     auto &Users = SeenDbgUsers[MO.getReg()];
1723480093f4SDimitry Andric     for (auto &User : Users) {
1724480093f4SDimitry Andric       MachineInstr *DbgMI = User.getPointer();
1725480093f4SDimitry Andric       if (User.getInt()) {
1726480093f4SDimitry Andric         // This DBG_VALUE would re-order assignments. If we can't copy-propagate
1727480093f4SDimitry Andric         // it, it can't be recovered. Set it undef.
1728fe6060f1SDimitry Andric         if (!attemptDebugCopyProp(MI, *DbgMI, MO.getReg()))
17295ffd83dbSDimitry Andric           DbgMI->setDebugValueUndef();
1730480093f4SDimitry Andric       } else {
1731fe6060f1SDimitry Andric         DbgUsersToSink.push_back(
1732fe6060f1SDimitry Andric             {DbgMI, SmallVector<unsigned, 2>(1, MO.getReg())});
1733480093f4SDimitry Andric       }
1734480093f4SDimitry Andric     }
1735480093f4SDimitry Andric   }
1736480093f4SDimitry Andric 
1737480093f4SDimitry Andric   // After sinking, some debug users may not be dominated any more. If possible,
1738480093f4SDimitry Andric   // copy-propagate their operands. As it's expensive, don't do this if there's
1739480093f4SDimitry Andric   // no debuginfo in the program.
1740480093f4SDimitry Andric   if (MI.getMF()->getFunction().getSubprogram() && MI.isCopy())
1741480093f4SDimitry Andric     SalvageUnsunkDebugUsersOfCopy(MI, SuccToSinkTo);
1742480093f4SDimitry Andric 
1743480093f4SDimitry Andric   performSink(MI, *SuccToSinkTo, InsertPos, DbgUsersToSink);
17440b57cec5SDimitry Andric 
17450b57cec5SDimitry Andric   // Conservatively, clear any kill flags, since it's possible that they are no
17460b57cec5SDimitry Andric   // longer correct.
17470b57cec5SDimitry Andric   // Note that we have to clear the kill flags for any register this instruction
17480b57cec5SDimitry Andric   // uses as we may sink over another instruction which currently kills the
17490b57cec5SDimitry Andric   // used registers.
1750fe013be4SDimitry Andric   for (MachineOperand &MO : MI.all_uses())
1751349cc55cSDimitry Andric     RegsToClearKillFlags.insert(MO.getReg()); // Remember to clear kill flags.
17520b57cec5SDimitry Andric 
17530b57cec5SDimitry Andric   return true;
17540b57cec5SDimitry Andric }
17550b57cec5SDimitry Andric 
SalvageUnsunkDebugUsersOfCopy(MachineInstr & MI,MachineBasicBlock * TargetBlock)1756480093f4SDimitry Andric void MachineSinking::SalvageUnsunkDebugUsersOfCopy(
1757480093f4SDimitry Andric     MachineInstr &MI, MachineBasicBlock *TargetBlock) {
1758480093f4SDimitry Andric   assert(MI.isCopy());
1759480093f4SDimitry Andric   assert(MI.getOperand(1).isReg());
1760480093f4SDimitry Andric 
1761480093f4SDimitry Andric   // Enumerate all users of vreg operands that are def'd. Skip those that will
1762480093f4SDimitry Andric   // be sunk. For the rest, if they are not dominated by the block we will sink
1763480093f4SDimitry Andric   // MI into, propagate the copy source to them.
1764480093f4SDimitry Andric   SmallVector<MachineInstr *, 4> DbgDefUsers;
1765fe6060f1SDimitry Andric   SmallVector<Register, 4> DbgUseRegs;
1766480093f4SDimitry Andric   const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1767fe013be4SDimitry Andric   for (auto &MO : MI.all_defs()) {
1768fe013be4SDimitry Andric     if (!MO.getReg().isVirtual())
1769480093f4SDimitry Andric       continue;
1770fe6060f1SDimitry Andric     DbgUseRegs.push_back(MO.getReg());
1771480093f4SDimitry Andric     for (auto &User : MRI.use_instructions(MO.getReg())) {
1772480093f4SDimitry Andric       if (!User.isDebugValue() || DT->dominates(TargetBlock, User.getParent()))
1773480093f4SDimitry Andric         continue;
1774480093f4SDimitry Andric 
1775480093f4SDimitry Andric       // If is in same block, will either sink or be use-before-def.
1776480093f4SDimitry Andric       if (User.getParent() == MI.getParent())
1777480093f4SDimitry Andric         continue;
1778480093f4SDimitry Andric 
1779fe6060f1SDimitry Andric       assert(User.hasDebugOperandForReg(MO.getReg()) &&
1780fe6060f1SDimitry Andric              "DBG_VALUE user of vreg, but has no operand for it?");
1781480093f4SDimitry Andric       DbgDefUsers.push_back(&User);
1782480093f4SDimitry Andric     }
1783480093f4SDimitry Andric   }
1784480093f4SDimitry Andric 
1785480093f4SDimitry Andric   // Point the users of this copy that are no longer dominated, at the source
1786480093f4SDimitry Andric   // of the copy.
1787480093f4SDimitry Andric   for (auto *User : DbgDefUsers) {
1788fe6060f1SDimitry Andric     for (auto &Reg : DbgUseRegs) {
1789fe6060f1SDimitry Andric       for (auto &DbgOp : User->getDebugOperandsForReg(Reg)) {
1790fe6060f1SDimitry Andric         DbgOp.setReg(MI.getOperand(1).getReg());
1791fe6060f1SDimitry Andric         DbgOp.setSubReg(MI.getOperand(1).getSubReg());
1792fe6060f1SDimitry Andric       }
1793fe6060f1SDimitry Andric     }
1794480093f4SDimitry Andric   }
1795480093f4SDimitry Andric }
1796480093f4SDimitry Andric 
17970b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
17980b57cec5SDimitry Andric // This pass is not intended to be a replacement or a complete alternative
17990b57cec5SDimitry Andric // for the pre-ra machine sink pass. It is only designed to sink COPY
18000b57cec5SDimitry Andric // instructions which should be handled after RA.
18010b57cec5SDimitry Andric //
18020b57cec5SDimitry Andric // This pass sinks COPY instructions into a successor block, if the COPY is not
18030b57cec5SDimitry Andric // used in the current block and the COPY is live-in to a single successor
18040b57cec5SDimitry Andric // (i.e., doesn't require the COPY to be duplicated).  This avoids executing the
18050b57cec5SDimitry Andric // copy on paths where their results aren't needed.  This also exposes
18060b57cec5SDimitry Andric // additional opportunites for dead copy elimination and shrink wrapping.
18070b57cec5SDimitry Andric //
18080b57cec5SDimitry Andric // These copies were either not handled by or are inserted after the MachineSink
18090b57cec5SDimitry Andric // pass. As an example of the former case, the MachineSink pass cannot sink
18100b57cec5SDimitry Andric // COPY instructions with allocatable source registers; for AArch64 these type
18110b57cec5SDimitry Andric // of copy instructions are frequently used to move function parameters (PhyReg)
18120b57cec5SDimitry Andric // into virtual registers in the entry block.
18130b57cec5SDimitry Andric //
18140b57cec5SDimitry Andric // For the machine IR below, this pass will sink %w19 in the entry into its
18150b57cec5SDimitry Andric // successor (%bb.1) because %w19 is only live-in in %bb.1.
18160b57cec5SDimitry Andric // %bb.0:
18170b57cec5SDimitry Andric //   %wzr = SUBSWri %w1, 1
18180b57cec5SDimitry Andric //   %w19 = COPY %w0
18190b57cec5SDimitry Andric //   Bcc 11, %bb.2
18200b57cec5SDimitry Andric // %bb.1:
18210b57cec5SDimitry Andric //   Live Ins: %w19
18220b57cec5SDimitry Andric //   BL @fun
18230b57cec5SDimitry Andric //   %w0 = ADDWrr %w0, %w19
18240b57cec5SDimitry Andric //   RET %w0
18250b57cec5SDimitry Andric // %bb.2:
18260b57cec5SDimitry Andric //   %w0 = COPY %wzr
18270b57cec5SDimitry Andric //   RET %w0
18280b57cec5SDimitry Andric // As we sink %w19 (CSR in AArch64) into %bb.1, the shrink-wrapping pass will be
18290b57cec5SDimitry Andric // able to see %bb.0 as a candidate.
18300b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
18310b57cec5SDimitry Andric namespace {
18320b57cec5SDimitry Andric 
18330b57cec5SDimitry Andric class PostRAMachineSinking : public MachineFunctionPass {
18340b57cec5SDimitry Andric public:
18350b57cec5SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
18360b57cec5SDimitry Andric 
18370b57cec5SDimitry Andric   static char ID;
PostRAMachineSinking()18380b57cec5SDimitry Andric   PostRAMachineSinking() : MachineFunctionPass(ID) {}
getPassName() const18390b57cec5SDimitry Andric   StringRef getPassName() const override { return "PostRA Machine Sink"; }
18400b57cec5SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const18410b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
18420b57cec5SDimitry Andric     AU.setPreservesCFG();
18430b57cec5SDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
18440b57cec5SDimitry Andric   }
18450b57cec5SDimitry Andric 
getRequiredProperties() const18460b57cec5SDimitry Andric   MachineFunctionProperties getRequiredProperties() const override {
18470b57cec5SDimitry Andric     return MachineFunctionProperties().set(
18480b57cec5SDimitry Andric         MachineFunctionProperties::Property::NoVRegs);
18490b57cec5SDimitry Andric   }
18500b57cec5SDimitry Andric 
18510b57cec5SDimitry Andric private:
18520b57cec5SDimitry Andric   /// Track which register units have been modified and used.
18530b57cec5SDimitry Andric   LiveRegUnits ModifiedRegUnits, UsedRegUnits;
18540b57cec5SDimitry Andric 
18558bcb0991SDimitry Andric   /// Track DBG_VALUEs of (unmodified) register units. Each DBG_VALUE has an
1856fe6060f1SDimitry Andric   /// entry in this map for each unit it touches. The DBG_VALUE's entry
1857fe6060f1SDimitry Andric   /// consists of a pointer to the instruction itself, and a vector of registers
1858fe6060f1SDimitry Andric   /// referred to by the instruction that overlap the key register unit.
1859fe6060f1SDimitry Andric   DenseMap<unsigned, SmallVector<MIRegs, 2>> SeenDbgInstrs;
18600b57cec5SDimitry Andric 
18610b57cec5SDimitry Andric   /// Sink Copy instructions unused in the same block close to their uses in
18620b57cec5SDimitry Andric   /// successors.
18630b57cec5SDimitry Andric   bool tryToSinkCopy(MachineBasicBlock &BB, MachineFunction &MF,
18640b57cec5SDimitry Andric                      const TargetRegisterInfo *TRI, const TargetInstrInfo *TII);
18650b57cec5SDimitry Andric };
18660b57cec5SDimitry Andric } // namespace
18670b57cec5SDimitry Andric 
18680b57cec5SDimitry Andric char PostRAMachineSinking::ID = 0;
18690b57cec5SDimitry Andric char &llvm::PostRAMachineSinkingID = PostRAMachineSinking::ID;
18700b57cec5SDimitry Andric 
18710b57cec5SDimitry Andric INITIALIZE_PASS(PostRAMachineSinking, "postra-machine-sink",
18720b57cec5SDimitry Andric                 "PostRA Machine Sink", false, false)
18730b57cec5SDimitry Andric 
aliasWithRegsInLiveIn(MachineBasicBlock & MBB,unsigned Reg,const TargetRegisterInfo * TRI)18740b57cec5SDimitry Andric static bool aliasWithRegsInLiveIn(MachineBasicBlock &MBB, unsigned Reg,
18750b57cec5SDimitry Andric                                   const TargetRegisterInfo *TRI) {
18760b57cec5SDimitry Andric   LiveRegUnits LiveInRegUnits(*TRI);
18770b57cec5SDimitry Andric   LiveInRegUnits.addLiveIns(MBB);
18780b57cec5SDimitry Andric   return !LiveInRegUnits.available(Reg);
18790b57cec5SDimitry Andric }
18800b57cec5SDimitry Andric 
18810b57cec5SDimitry Andric static MachineBasicBlock *
getSingleLiveInSuccBB(MachineBasicBlock & CurBB,const SmallPtrSetImpl<MachineBasicBlock * > & SinkableBBs,unsigned Reg,const TargetRegisterInfo * TRI)18820b57cec5SDimitry Andric getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
18830b57cec5SDimitry Andric                       const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
18840b57cec5SDimitry Andric                       unsigned Reg, const TargetRegisterInfo *TRI) {
18850b57cec5SDimitry Andric   // Try to find a single sinkable successor in which Reg is live-in.
18860b57cec5SDimitry Andric   MachineBasicBlock *BB = nullptr;
18870b57cec5SDimitry Andric   for (auto *SI : SinkableBBs) {
18880b57cec5SDimitry Andric     if (aliasWithRegsInLiveIn(*SI, Reg, TRI)) {
18890b57cec5SDimitry Andric       // If BB is set here, Reg is live-in to at least two sinkable successors,
18900b57cec5SDimitry Andric       // so quit.
18910b57cec5SDimitry Andric       if (BB)
18920b57cec5SDimitry Andric         return nullptr;
18930b57cec5SDimitry Andric       BB = SI;
18940b57cec5SDimitry Andric     }
18950b57cec5SDimitry Andric   }
18960b57cec5SDimitry Andric   // Reg is not live-in to any sinkable successors.
18970b57cec5SDimitry Andric   if (!BB)
18980b57cec5SDimitry Andric     return nullptr;
18990b57cec5SDimitry Andric 
19000b57cec5SDimitry Andric   // Check if any register aliased with Reg is live-in in other successors.
19010b57cec5SDimitry Andric   for (auto *SI : CurBB.successors()) {
19020b57cec5SDimitry Andric     if (!SinkableBBs.count(SI) && aliasWithRegsInLiveIn(*SI, Reg, TRI))
19030b57cec5SDimitry Andric       return nullptr;
19040b57cec5SDimitry Andric   }
19050b57cec5SDimitry Andric   return BB;
19060b57cec5SDimitry Andric }
19070b57cec5SDimitry Andric 
19080b57cec5SDimitry Andric static MachineBasicBlock *
getSingleLiveInSuccBB(MachineBasicBlock & CurBB,const SmallPtrSetImpl<MachineBasicBlock * > & SinkableBBs,ArrayRef<unsigned> DefedRegsInCopy,const TargetRegisterInfo * TRI)19090b57cec5SDimitry Andric getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
19100b57cec5SDimitry Andric                       const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
19110b57cec5SDimitry Andric                       ArrayRef<unsigned> DefedRegsInCopy,
19120b57cec5SDimitry Andric                       const TargetRegisterInfo *TRI) {
19130b57cec5SDimitry Andric   MachineBasicBlock *SingleBB = nullptr;
19140b57cec5SDimitry Andric   for (auto DefReg : DefedRegsInCopy) {
19150b57cec5SDimitry Andric     MachineBasicBlock *BB =
19160b57cec5SDimitry Andric         getSingleLiveInSuccBB(CurBB, SinkableBBs, DefReg, TRI);
19170b57cec5SDimitry Andric     if (!BB || (SingleBB && SingleBB != BB))
19180b57cec5SDimitry Andric       return nullptr;
19190b57cec5SDimitry Andric     SingleBB = BB;
19200b57cec5SDimitry Andric   }
19210b57cec5SDimitry Andric   return SingleBB;
19220b57cec5SDimitry Andric }
19230b57cec5SDimitry Andric 
clearKillFlags(MachineInstr * MI,MachineBasicBlock & CurBB,SmallVectorImpl<unsigned> & UsedOpsInCopy,LiveRegUnits & UsedRegUnits,const TargetRegisterInfo * TRI)19240b57cec5SDimitry Andric static void clearKillFlags(MachineInstr *MI, MachineBasicBlock &CurBB,
19250b57cec5SDimitry Andric                            SmallVectorImpl<unsigned> &UsedOpsInCopy,
19260b57cec5SDimitry Andric                            LiveRegUnits &UsedRegUnits,
19270b57cec5SDimitry Andric                            const TargetRegisterInfo *TRI) {
19280b57cec5SDimitry Andric   for (auto U : UsedOpsInCopy) {
19290b57cec5SDimitry Andric     MachineOperand &MO = MI->getOperand(U);
19308bcb0991SDimitry Andric     Register SrcReg = MO.getReg();
19310b57cec5SDimitry Andric     if (!UsedRegUnits.available(SrcReg)) {
19320b57cec5SDimitry Andric       MachineBasicBlock::iterator NI = std::next(MI->getIterator());
19330b57cec5SDimitry Andric       for (MachineInstr &UI : make_range(NI, CurBB.end())) {
19340b57cec5SDimitry Andric         if (UI.killsRegister(SrcReg, TRI)) {
19350b57cec5SDimitry Andric           UI.clearRegisterKills(SrcReg, TRI);
19360b57cec5SDimitry Andric           MO.setIsKill(true);
19370b57cec5SDimitry Andric           break;
19380b57cec5SDimitry Andric         }
19390b57cec5SDimitry Andric       }
19400b57cec5SDimitry Andric     }
19410b57cec5SDimitry Andric   }
19420b57cec5SDimitry Andric }
19430b57cec5SDimitry Andric 
updateLiveIn(MachineInstr * MI,MachineBasicBlock * SuccBB,SmallVectorImpl<unsigned> & UsedOpsInCopy,SmallVectorImpl<unsigned> & DefedRegsInCopy)19440b57cec5SDimitry Andric static void updateLiveIn(MachineInstr *MI, MachineBasicBlock *SuccBB,
19450b57cec5SDimitry Andric                          SmallVectorImpl<unsigned> &UsedOpsInCopy,
19460b57cec5SDimitry Andric                          SmallVectorImpl<unsigned> &DefedRegsInCopy) {
19470b57cec5SDimitry Andric   MachineFunction &MF = *SuccBB->getParent();
19480b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
19490b57cec5SDimitry Andric   for (unsigned DefReg : DefedRegsInCopy)
1950fe013be4SDimitry Andric     for (MCPhysReg S : TRI->subregs_inclusive(DefReg))
1951fe013be4SDimitry Andric       SuccBB->removeLiveIn(S);
19520b57cec5SDimitry Andric   for (auto U : UsedOpsInCopy) {
1953480093f4SDimitry Andric     Register SrcReg = MI->getOperand(U).getReg();
1954480093f4SDimitry Andric     LaneBitmask Mask;
1955*c9157d92SDimitry Andric     for (MCRegUnitMaskIterator S(SrcReg, TRI); S.isValid(); ++S)
1956480093f4SDimitry Andric       Mask |= (*S).second;
1957*c9157d92SDimitry Andric     SuccBB->addLiveIn(SrcReg, Mask);
1958480093f4SDimitry Andric   }
1959480093f4SDimitry Andric   SuccBB->sortUniqueLiveIns();
19600b57cec5SDimitry Andric }
19610b57cec5SDimitry Andric 
hasRegisterDependency(MachineInstr * MI,SmallVectorImpl<unsigned> & UsedOpsInCopy,SmallVectorImpl<unsigned> & DefedRegsInCopy,LiveRegUnits & ModifiedRegUnits,LiveRegUnits & UsedRegUnits)19620b57cec5SDimitry Andric static bool hasRegisterDependency(MachineInstr *MI,
19630b57cec5SDimitry Andric                                   SmallVectorImpl<unsigned> &UsedOpsInCopy,
19640b57cec5SDimitry Andric                                   SmallVectorImpl<unsigned> &DefedRegsInCopy,
19650b57cec5SDimitry Andric                                   LiveRegUnits &ModifiedRegUnits,
19660b57cec5SDimitry Andric                                   LiveRegUnits &UsedRegUnits) {
19670b57cec5SDimitry Andric   bool HasRegDependency = false;
19680b57cec5SDimitry Andric   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
19690b57cec5SDimitry Andric     MachineOperand &MO = MI->getOperand(i);
19700b57cec5SDimitry Andric     if (!MO.isReg())
19710b57cec5SDimitry Andric       continue;
19728bcb0991SDimitry Andric     Register Reg = MO.getReg();
19730b57cec5SDimitry Andric     if (!Reg)
19740b57cec5SDimitry Andric       continue;
19750b57cec5SDimitry Andric     if (MO.isDef()) {
19760b57cec5SDimitry Andric       if (!ModifiedRegUnits.available(Reg) || !UsedRegUnits.available(Reg)) {
19770b57cec5SDimitry Andric         HasRegDependency = true;
19780b57cec5SDimitry Andric         break;
19790b57cec5SDimitry Andric       }
19800b57cec5SDimitry Andric       DefedRegsInCopy.push_back(Reg);
19810b57cec5SDimitry Andric 
19820b57cec5SDimitry Andric       // FIXME: instead of isUse(), readsReg() would be a better fix here,
19830b57cec5SDimitry Andric       // For example, we can ignore modifications in reg with undef. However,
19840b57cec5SDimitry Andric       // it's not perfectly clear if skipping the internal read is safe in all
19850b57cec5SDimitry Andric       // other targets.
19860b57cec5SDimitry Andric     } else if (MO.isUse()) {
19870b57cec5SDimitry Andric       if (!ModifiedRegUnits.available(Reg)) {
19880b57cec5SDimitry Andric         HasRegDependency = true;
19890b57cec5SDimitry Andric         break;
19900b57cec5SDimitry Andric       }
19910b57cec5SDimitry Andric       UsedOpsInCopy.push_back(i);
19920b57cec5SDimitry Andric     }
19930b57cec5SDimitry Andric   }
19940b57cec5SDimitry Andric   return HasRegDependency;
19950b57cec5SDimitry Andric }
19960b57cec5SDimitry Andric 
tryToSinkCopy(MachineBasicBlock & CurBB,MachineFunction & MF,const TargetRegisterInfo * TRI,const TargetInstrInfo * TII)19970b57cec5SDimitry Andric bool PostRAMachineSinking::tryToSinkCopy(MachineBasicBlock &CurBB,
19980b57cec5SDimitry Andric                                          MachineFunction &MF,
19990b57cec5SDimitry Andric                                          const TargetRegisterInfo *TRI,
20000b57cec5SDimitry Andric                                          const TargetInstrInfo *TII) {
20010b57cec5SDimitry Andric   SmallPtrSet<MachineBasicBlock *, 2> SinkableBBs;
20020b57cec5SDimitry Andric   // FIXME: For now, we sink only to a successor which has a single predecessor
20030b57cec5SDimitry Andric   // so that we can directly sink COPY instructions to the successor without
20040b57cec5SDimitry Andric   // adding any new block or branch instruction.
20050b57cec5SDimitry Andric   for (MachineBasicBlock *SI : CurBB.successors())
20060b57cec5SDimitry Andric     if (!SI->livein_empty() && SI->pred_size() == 1)
20070b57cec5SDimitry Andric       SinkableBBs.insert(SI);
20080b57cec5SDimitry Andric 
20090b57cec5SDimitry Andric   if (SinkableBBs.empty())
20100b57cec5SDimitry Andric     return false;
20110b57cec5SDimitry Andric 
20120b57cec5SDimitry Andric   bool Changed = false;
20130b57cec5SDimitry Andric 
20140b57cec5SDimitry Andric   // Track which registers have been modified and used between the end of the
20150b57cec5SDimitry Andric   // block and the current instruction.
20160b57cec5SDimitry Andric   ModifiedRegUnits.clear();
20170b57cec5SDimitry Andric   UsedRegUnits.clear();
20180b57cec5SDimitry Andric   SeenDbgInstrs.clear();
20190b57cec5SDimitry Andric 
2020349cc55cSDimitry Andric   for (MachineInstr &MI : llvm::make_early_inc_range(llvm::reverse(CurBB))) {
20210b57cec5SDimitry Andric     // Track the operand index for use in Copy.
20220b57cec5SDimitry Andric     SmallVector<unsigned, 2> UsedOpsInCopy;
20230b57cec5SDimitry Andric     // Track the register number defed in Copy.
20240b57cec5SDimitry Andric     SmallVector<unsigned, 2> DefedRegsInCopy;
20250b57cec5SDimitry Andric 
20260b57cec5SDimitry Andric     // We must sink this DBG_VALUE if its operand is sunk. To avoid searching
20270b57cec5SDimitry Andric     // for DBG_VALUEs later, record them when they're encountered.
2028bdd1243dSDimitry Andric     if (MI.isDebugValue() && !MI.isDebugRef()) {
2029fe6060f1SDimitry Andric       SmallDenseMap<MCRegister, SmallVector<unsigned, 2>, 4> MIUnits;
2030fe6060f1SDimitry Andric       bool IsValid = true;
2031349cc55cSDimitry Andric       for (MachineOperand &MO : MI.debug_operands()) {
2032bdd1243dSDimitry Andric         if (MO.isReg() && MO.getReg().isPhysical()) {
20330b57cec5SDimitry Andric           // Bail if we can already tell the sink would be rejected, rather
20340b57cec5SDimitry Andric           // than needlessly accumulating lots of DBG_VALUEs.
2035349cc55cSDimitry Andric           if (hasRegisterDependency(&MI, UsedOpsInCopy, DefedRegsInCopy,
2036fe6060f1SDimitry Andric                                     ModifiedRegUnits, UsedRegUnits)) {
2037fe6060f1SDimitry Andric             IsValid = false;
2038fe6060f1SDimitry Andric             break;
2039fe6060f1SDimitry Andric           }
20400b57cec5SDimitry Andric 
20418bcb0991SDimitry Andric           // Record debug use of each reg unit.
2042fe013be4SDimitry Andric           for (MCRegUnit Unit : TRI->regunits(MO.getReg()))
2043fe013be4SDimitry Andric             MIUnits[Unit].push_back(MO.getReg());
2044fe6060f1SDimitry Andric         }
2045fe6060f1SDimitry Andric       }
2046fe6060f1SDimitry Andric       if (IsValid) {
204781ad6265SDimitry Andric         for (auto &RegOps : MIUnits)
204881ad6265SDimitry Andric           SeenDbgInstrs[RegOps.first].emplace_back(&MI,
204981ad6265SDimitry Andric                                                    std::move(RegOps.second));
20500b57cec5SDimitry Andric       }
20510b57cec5SDimitry Andric       continue;
20520b57cec5SDimitry Andric     }
20530b57cec5SDimitry Andric 
2054349cc55cSDimitry Andric     if (MI.isDebugOrPseudoInstr())
20550b57cec5SDimitry Andric       continue;
20560b57cec5SDimitry Andric 
20570b57cec5SDimitry Andric     // Do not move any instruction across function call.
2058349cc55cSDimitry Andric     if (MI.isCall())
20590b57cec5SDimitry Andric       return false;
20600b57cec5SDimitry Andric 
2061349cc55cSDimitry Andric     if (!MI.isCopy() || !MI.getOperand(0).isRenamable()) {
2062349cc55cSDimitry Andric       LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
20630b57cec5SDimitry Andric                                         TRI);
20640b57cec5SDimitry Andric       continue;
20650b57cec5SDimitry Andric     }
20660b57cec5SDimitry Andric 
20670b57cec5SDimitry Andric     // Don't sink the COPY if it would violate a register dependency.
2068349cc55cSDimitry Andric     if (hasRegisterDependency(&MI, UsedOpsInCopy, DefedRegsInCopy,
20690b57cec5SDimitry Andric                               ModifiedRegUnits, UsedRegUnits)) {
2070349cc55cSDimitry Andric       LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
20710b57cec5SDimitry Andric                                         TRI);
20720b57cec5SDimitry Andric       continue;
20730b57cec5SDimitry Andric     }
20740b57cec5SDimitry Andric     assert((!UsedOpsInCopy.empty() && !DefedRegsInCopy.empty()) &&
20750b57cec5SDimitry Andric            "Unexpect SrcReg or DefReg");
20760b57cec5SDimitry Andric     MachineBasicBlock *SuccBB =
20770b57cec5SDimitry Andric         getSingleLiveInSuccBB(CurBB, SinkableBBs, DefedRegsInCopy, TRI);
20780b57cec5SDimitry Andric     // Don't sink if we cannot find a single sinkable successor in which Reg
20790b57cec5SDimitry Andric     // is live-in.
20800b57cec5SDimitry Andric     if (!SuccBB) {
2081349cc55cSDimitry Andric       LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
20820b57cec5SDimitry Andric                                         TRI);
20830b57cec5SDimitry Andric       continue;
20840b57cec5SDimitry Andric     }
20850b57cec5SDimitry Andric     assert((SuccBB->pred_size() == 1 && *SuccBB->pred_begin() == &CurBB) &&
20860b57cec5SDimitry Andric            "Unexpected predecessor");
20870b57cec5SDimitry Andric 
20888bcb0991SDimitry Andric     // Collect DBG_VALUEs that must sink with this copy. We've previously
20898bcb0991SDimitry Andric     // recorded which reg units that DBG_VALUEs read, if this instruction
20908bcb0991SDimitry Andric     // writes any of those units then the corresponding DBG_VALUEs must sink.
2091fe6060f1SDimitry Andric     MapVector<MachineInstr *, MIRegs::second_type> DbgValsToSinkMap;
2092fe013be4SDimitry Andric     for (auto &MO : MI.all_defs()) {
2093fe013be4SDimitry Andric       for (MCRegUnit Unit : TRI->regunits(MO.getReg())) {
2094fe013be4SDimitry Andric         for (const auto &MIRegs : SeenDbgInstrs.lookup(Unit)) {
2095fe6060f1SDimitry Andric           auto &Regs = DbgValsToSinkMap[MIRegs.first];
2096fe6060f1SDimitry Andric           for (unsigned Reg : MIRegs.second)
2097fe6060f1SDimitry Andric             Regs.push_back(Reg);
20980b57cec5SDimitry Andric         }
2099fe6060f1SDimitry Andric       }
2100fe6060f1SDimitry Andric     }
210181ad6265SDimitry Andric     auto DbgValsToSink = DbgValsToSinkMap.takeVector();
210281ad6265SDimitry Andric 
210381ad6265SDimitry Andric     LLVM_DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccBB);
210481ad6265SDimitry Andric 
210581ad6265SDimitry Andric     MachineBasicBlock::iterator InsertPos =
210681ad6265SDimitry Andric         SuccBB->SkipPHIsAndLabels(SuccBB->begin());
210781ad6265SDimitry Andric     if (blockPrologueInterferes(SuccBB, InsertPos, MI, TRI, TII, nullptr)) {
210881ad6265SDimitry Andric       LLVM_DEBUG(
210981ad6265SDimitry Andric           dbgs() << " *** Not sinking: prologue interference\n");
211081ad6265SDimitry Andric       continue;
211181ad6265SDimitry Andric     }
21120b57cec5SDimitry Andric 
21130b57cec5SDimitry Andric     // Clear the kill flag if SrcReg is killed between MI and the end of the
21140b57cec5SDimitry Andric     // block.
2115349cc55cSDimitry Andric     clearKillFlags(&MI, CurBB, UsedOpsInCopy, UsedRegUnits, TRI);
2116349cc55cSDimitry Andric     performSink(MI, *SuccBB, InsertPos, DbgValsToSink);
2117349cc55cSDimitry Andric     updateLiveIn(&MI, SuccBB, UsedOpsInCopy, DefedRegsInCopy);
21180b57cec5SDimitry Andric 
21190b57cec5SDimitry Andric     Changed = true;
21200b57cec5SDimitry Andric     ++NumPostRACopySink;
21210b57cec5SDimitry Andric   }
21220b57cec5SDimitry Andric   return Changed;
21230b57cec5SDimitry Andric }
21240b57cec5SDimitry Andric 
runOnMachineFunction(MachineFunction & MF)21250b57cec5SDimitry Andric bool PostRAMachineSinking::runOnMachineFunction(MachineFunction &MF) {
21260b57cec5SDimitry Andric   if (skipFunction(MF.getFunction()))
21270b57cec5SDimitry Andric     return false;
21280b57cec5SDimitry Andric 
21290b57cec5SDimitry Andric   bool Changed = false;
21300b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
21310b57cec5SDimitry Andric   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
21320b57cec5SDimitry Andric 
21330b57cec5SDimitry Andric   ModifiedRegUnits.init(*TRI);
21340b57cec5SDimitry Andric   UsedRegUnits.init(*TRI);
21350b57cec5SDimitry Andric   for (auto &BB : MF)
21360b57cec5SDimitry Andric     Changed |= tryToSinkCopy(BB, MF, TRI, TII);
21370b57cec5SDimitry Andric 
21380b57cec5SDimitry Andric   return Changed;
21390b57cec5SDimitry Andric }
2140