12cab237bSDimitry Andric //===- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ----------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This pass performs loop invariant code motion on machine instructions. We
11f22ef01cSRoman Divacky // attempt to remove as much code from the body of a loop as possible.
12f22ef01cSRoman Divacky //
13f22ef01cSRoman Divacky // This pass is not intended to be a replacement or a complete alternative
14f22ef01cSRoman Divacky // for the LLVM-IR-level LICM pass. It is only designed to hoist simple
15f22ef01cSRoman Divacky // constructs that are not exposed before lowering and instruction selection.
16f22ef01cSRoman Divacky //
17f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
18f22ef01cSRoman Divacky 
192cab237bSDimitry Andric #include "llvm/ADT/BitVector.h"
20139f7f9bSDimitry Andric #include "llvm/ADT/DenseMap.h"
212cab237bSDimitry Andric #include "llvm/ADT/STLExtras.h"
22139f7f9bSDimitry Andric #include "llvm/ADT/SmallSet.h"
232cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h"
24139f7f9bSDimitry Andric #include "llvm/ADT/Statistic.h"
25139f7f9bSDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
262cab237bSDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
27f22ef01cSRoman Divacky #include "llvm/CodeGen/MachineDominators.h"
28f22ef01cSRoman Divacky #include "llvm/CodeGen/MachineFrameInfo.h"
292cab237bSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
302cab237bSDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
312cab237bSDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
32f22ef01cSRoman Divacky #include "llvm/CodeGen/MachineLoopInfo.h"
33f22ef01cSRoman Divacky #include "llvm/CodeGen/MachineMemOperand.h"
342cab237bSDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
35f22ef01cSRoman Divacky #include "llvm/CodeGen/MachineRegisterInfo.h"
36f22ef01cSRoman Divacky #include "llvm/CodeGen/PseudoSourceValue.h"
372cab237bSDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
382cab237bSDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
392cab237bSDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
408f0fd8f6SDimitry Andric #include "llvm/CodeGen/TargetSchedule.h"
412cab237bSDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
422cab237bSDimitry Andric #include "llvm/IR/DebugLoc.h"
432cab237bSDimitry Andric #include "llvm/MC/MCInstrDesc.h"
442cab237bSDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
452cab237bSDimitry Andric #include "llvm/Pass.h"
462cab237bSDimitry Andric #include "llvm/Support/Casting.h"
476122f3e6SDimitry Andric #include "llvm/Support/CommandLine.h"
48f22ef01cSRoman Divacky #include "llvm/Support/Debug.h"
49f22ef01cSRoman Divacky #include "llvm/Support/raw_ostream.h"
502cab237bSDimitry Andric #include <algorithm>
512cab237bSDimitry Andric #include <cassert>
522cab237bSDimitry Andric #include <limits>
532cab237bSDimitry Andric #include <vector>
542cab237bSDimitry Andric 
55f22ef01cSRoman Divacky using namespace llvm;
56f22ef01cSRoman Divacky 
57302affcbSDimitry Andric #define DEBUG_TYPE "machinelicm"
5891bc56edSDimitry Andric 
596122f3e6SDimitry Andric static cl::opt<bool>
606122f3e6SDimitry Andric AvoidSpeculation("avoid-speculation",
616122f3e6SDimitry Andric                  cl::desc("MachineLICM should avoid speculation"),
62dff0c46cSDimitry Andric                  cl::init(true), cl::Hidden);
636122f3e6SDimitry Andric 
6439d628a0SDimitry Andric static cl::opt<bool>
6539d628a0SDimitry Andric HoistCheapInsts("hoist-cheap-insts",
6639d628a0SDimitry Andric                 cl::desc("MachineLICM should hoist even cheap instructions"),
6739d628a0SDimitry Andric                 cl::init(false), cl::Hidden);
6839d628a0SDimitry Andric 
69ff0cc061SDimitry Andric static cl::opt<bool>
70ff0cc061SDimitry Andric SinkInstsToAvoidSpills("sink-insts-to-avoid-spills",
71ff0cc061SDimitry Andric                        cl::desc("MachineLICM should sink instructions into "
72ff0cc061SDimitry Andric                                 "loops to avoid register spills"),
73ff0cc061SDimitry Andric                        cl::init(false), cl::Hidden);
744ba319b5SDimitry Andric static cl::opt<bool>
754ba319b5SDimitry Andric HoistConstStores("hoist-const-stores",
764ba319b5SDimitry Andric                  cl::desc("Hoist invariant stores"),
774ba319b5SDimitry Andric                  cl::init(true), cl::Hidden);
78ff0cc061SDimitry Andric 
792754fe60SDimitry Andric STATISTIC(NumHoisted,
802754fe60SDimitry Andric           "Number of machine instructions hoisted out of loops");
812754fe60SDimitry Andric STATISTIC(NumLowRP,
822754fe60SDimitry Andric           "Number of instructions hoisted in low reg pressure situation");
832754fe60SDimitry Andric STATISTIC(NumHighLatency,
842754fe60SDimitry Andric           "Number of high latency instructions hoisted");
852754fe60SDimitry Andric STATISTIC(NumCSEed,
862754fe60SDimitry Andric           "Number of hoisted machine instructions CSEed");
87f22ef01cSRoman Divacky STATISTIC(NumPostRAHoisted,
88f22ef01cSRoman Divacky           "Number of machine instructions hoisted out of loops post regalloc");
894ba319b5SDimitry Andric STATISTIC(NumStoreConst,
904ba319b5SDimitry Andric           "Number of stores of const phys reg hoisted out of loops");
91f22ef01cSRoman Divacky 
92f22ef01cSRoman Divacky namespace {
932cab237bSDimitry Andric 
944ba319b5SDimitry Andric   class MachineLICMBase : public MachineFunctionPass {
95f22ef01cSRoman Divacky     const TargetInstrInfo *TII;
96139f7f9bSDimitry Andric     const TargetLoweringBase *TLI;
97f22ef01cSRoman Divacky     const TargetRegisterInfo *TRI;
98f22ef01cSRoman Divacky     const MachineFrameInfo *MFI;
992754fe60SDimitry Andric     MachineRegisterInfo *MRI;
1008f0fd8f6SDimitry Andric     TargetSchedModel SchedModel;
1014ba319b5SDimitry Andric     bool PreRegAlloc;
102f22ef01cSRoman Divacky 
103f22ef01cSRoman Divacky     // Various analyses that we use...
104f22ef01cSRoman Divacky     AliasAnalysis        *AA;      // Alias analysis info.
105f22ef01cSRoman Divacky     MachineLoopInfo      *MLI;     // Current MachineLoopInfo
106f22ef01cSRoman Divacky     MachineDominatorTree *DT;      // Machine dominator tree for the cur loop
107f22ef01cSRoman Divacky 
108f22ef01cSRoman Divacky     // State that is updated as we process loops
109f22ef01cSRoman Divacky     bool         Changed;          // True if a loop is changed.
110ffd1746dSEd Schouten     bool         FirstInLoop;      // True if it's the first LICM in the loop.
111f22ef01cSRoman Divacky     MachineLoop *CurLoop;          // The current loop we are working on.
112f22ef01cSRoman Divacky     MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
113f22ef01cSRoman Divacky 
114dff0c46cSDimitry Andric     // Exit blocks for CurLoop.
115dff0c46cSDimitry Andric     SmallVector<MachineBasicBlock *, 8> ExitBlocks;
116dff0c46cSDimitry Andric 
isExitBlock(const MachineBasicBlock * MBB) const117dff0c46cSDimitry Andric     bool isExitBlock(const MachineBasicBlock *MBB) const {
118d88c1a5aSDimitry Andric       return is_contained(ExitBlocks, MBB);
119dff0c46cSDimitry Andric     }
120f22ef01cSRoman Divacky 
1212754fe60SDimitry Andric     // Track 'estimated' register pressure.
1222754fe60SDimitry Andric     SmallSet<unsigned, 32> RegSeen;
1232754fe60SDimitry Andric     SmallVector<unsigned, 8> RegPressure;
1242754fe60SDimitry Andric 
125ff0cc061SDimitry Andric     // Register pressure "limit" per register pressure set. If the pressure
1262754fe60SDimitry Andric     // is higher than the limit, then it's considered high.
1272754fe60SDimitry Andric     SmallVector<unsigned, 8> RegLimit;
1282754fe60SDimitry Andric 
1292754fe60SDimitry Andric     // Register pressure on path leading from loop preheader to current BB.
1302754fe60SDimitry Andric     SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
1312754fe60SDimitry Andric 
132e580952dSDimitry Andric     // For each opcode, keep a list of potential CSE instructions.
133f22ef01cSRoman Divacky     DenseMap<unsigned, std::vector<const MachineInstr *>> CSEMap;
134f22ef01cSRoman Divacky 
1356122f3e6SDimitry Andric     enum {
1366122f3e6SDimitry Andric       SpeculateFalse   = 0,
1376122f3e6SDimitry Andric       SpeculateTrue    = 1,
1386122f3e6SDimitry Andric       SpeculateUnknown = 2
1396122f3e6SDimitry Andric     };
1406122f3e6SDimitry Andric 
1416122f3e6SDimitry Andric     // If a MBB does not dominate loop exiting blocks then it may not safe
1426122f3e6SDimitry Andric     // to hoist loads from this block.
1436122f3e6SDimitry Andric     // Tri-state: 0 - false, 1 - true, 2 - unknown
1446122f3e6SDimitry Andric     unsigned SpeculationState;
1456122f3e6SDimitry Andric 
146f22ef01cSRoman Divacky   public:
MachineLICMBase(char & PassID,bool PreRegAlloc)1474ba319b5SDimitry Andric     MachineLICMBase(char &PassID, bool PreRegAlloc)
1484ba319b5SDimitry Andric         : MachineFunctionPass(PassID), PreRegAlloc(PreRegAlloc) {}
149f22ef01cSRoman Divacky 
15091bc56edSDimitry Andric     bool runOnMachineFunction(MachineFunction &MF) override;
151f22ef01cSRoman Divacky 
getAnalysisUsage(AnalysisUsage & AU) const15291bc56edSDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
153f22ef01cSRoman Divacky       AU.addRequired<MachineLoopInfo>();
154f22ef01cSRoman Divacky       AU.addRequired<MachineDominatorTree>();
1557d523365SDimitry Andric       AU.addRequired<AAResultsWrapperPass>();
156f22ef01cSRoman Divacky       AU.addPreserved<MachineLoopInfo>();
157f22ef01cSRoman Divacky       AU.addPreserved<MachineDominatorTree>();
158f22ef01cSRoman Divacky       MachineFunctionPass::getAnalysisUsage(AU);
159f22ef01cSRoman Divacky     }
160f22ef01cSRoman Divacky 
releaseMemory()16191bc56edSDimitry Andric     void releaseMemory() override {
1622754fe60SDimitry Andric       RegSeen.clear();
1632754fe60SDimitry Andric       RegPressure.clear();
1642754fe60SDimitry Andric       RegLimit.clear();
1652754fe60SDimitry Andric       BackTrace.clear();
166f22ef01cSRoman Divacky       CSEMap.clear();
167f22ef01cSRoman Divacky     }
168f22ef01cSRoman Divacky 
169f22ef01cSRoman Divacky   private:
1707d523365SDimitry Andric     /// Keep track of information about hoisting candidates.
171f22ef01cSRoman Divacky     struct CandidateInfo {
172f22ef01cSRoman Divacky       MachineInstr *MI;
173f22ef01cSRoman Divacky       unsigned      Def;
174f22ef01cSRoman Divacky       int           FI;
1752cab237bSDimitry Andric 
CandidateInfo__anona8a949b30111::MachineLICMBase::CandidateInfo176f22ef01cSRoman Divacky       CandidateInfo(MachineInstr *mi, unsigned def, int fi)
177f22ef01cSRoman Divacky         : MI(mi), Def(def), FI(fi) {}
178f22ef01cSRoman Divacky     };
179f22ef01cSRoman Divacky 
180f22ef01cSRoman Divacky     void HoistRegionPostRA();
181f22ef01cSRoman Divacky 
182f22ef01cSRoman Divacky     void HoistPostRA(MachineInstr *MI, unsigned Def);
183f22ef01cSRoman Divacky 
1847d523365SDimitry Andric     void ProcessMI(MachineInstr *MI, BitVector &PhysRegDefs,
1857d523365SDimitry Andric                    BitVector &PhysRegClobbers, SmallSet<int, 32> &StoredFIs,
186f785676fSDimitry Andric                    SmallVectorImpl<CandidateInfo> &Candidates);
187f22ef01cSRoman Divacky 
188f22ef01cSRoman Divacky     void AddToLiveIns(unsigned Reg);
189f22ef01cSRoman Divacky 
190f22ef01cSRoman Divacky     bool IsLICMCandidate(MachineInstr &I);
191f22ef01cSRoman Divacky 
192f22ef01cSRoman Divacky     bool IsLoopInvariantInst(MachineInstr &I);
193f22ef01cSRoman Divacky 
194dff0c46cSDimitry Andric     bool HasLoopPHIUse(const MachineInstr *MI) const;
1953b0f4066SDimitry Andric 
1962754fe60SDimitry Andric     bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
1972754fe60SDimitry Andric                                unsigned Reg) const;
1982754fe60SDimitry Andric 
1992754fe60SDimitry Andric     bool IsCheapInstruction(MachineInstr &MI) const;
2002754fe60SDimitry Andric 
201ff0cc061SDimitry Andric     bool CanCauseHighRegPressure(const DenseMap<unsigned, int> &Cost,
202ff0cc061SDimitry Andric                                  bool Cheap);
2032754fe60SDimitry Andric 
2042754fe60SDimitry Andric     void UpdateBackTraceRegPressure(const MachineInstr *MI);
2052754fe60SDimitry Andric 
206f22ef01cSRoman Divacky     bool IsProfitableToHoist(MachineInstr &MI);
207f22ef01cSRoman Divacky 
2086122f3e6SDimitry Andric     bool IsGuaranteedToExecute(MachineBasicBlock *BB);
2096122f3e6SDimitry Andric 
210dff0c46cSDimitry Andric     void EnterScope(MachineBasicBlock *MBB);
211dff0c46cSDimitry Andric 
212dff0c46cSDimitry Andric     void ExitScope(MachineBasicBlock *MBB);
213dff0c46cSDimitry Andric 
2147d523365SDimitry Andric     void ExitScopeIfDone(
2157d523365SDimitry Andric         MachineDomTreeNode *Node,
216dff0c46cSDimitry Andric         DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren,
217dff0c46cSDimitry Andric         DenseMap<MachineDomTreeNode *, MachineDomTreeNode *> &ParentMap);
218dff0c46cSDimitry Andric 
2194ba319b5SDimitry Andric     void HoistOutOfLoop(MachineDomTreeNode *HeaderN);
2207d523365SDimitry Andric 
221dff0c46cSDimitry Andric     void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
222f22ef01cSRoman Divacky 
223ff0cc061SDimitry Andric     void SinkIntoLoop();
2246122f3e6SDimitry Andric 
2252754fe60SDimitry Andric     void InitRegPressure(MachineBasicBlock *BB);
2262754fe60SDimitry Andric 
227ff0cc061SDimitry Andric     DenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI,
228ff0cc061SDimitry Andric                                              bool ConsiderSeen,
229ff0cc061SDimitry Andric                                              bool ConsiderUnseenAsDef);
230ff0cc061SDimitry Andric 
231ff0cc061SDimitry Andric     void UpdateRegPressure(const MachineInstr *MI,
232ff0cc061SDimitry Andric                            bool ConsiderUnseenAsDef = false);
233f22ef01cSRoman Divacky 
234f22ef01cSRoman Divacky     MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
235f22ef01cSRoman Divacky 
2367d523365SDimitry Andric     const MachineInstr *
2377d523365SDimitry Andric     LookForDuplicate(const MachineInstr *MI,
238f22ef01cSRoman Divacky                      std::vector<const MachineInstr *> &PrevMIs);
239f22ef01cSRoman Divacky 
2407d523365SDimitry Andric     bool EliminateCSE(
2417d523365SDimitry Andric         MachineInstr *MI,
242f22ef01cSRoman Divacky         DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI);
243f22ef01cSRoman Divacky 
2446122f3e6SDimitry Andric     bool MayCSE(MachineInstr *MI);
2456122f3e6SDimitry Andric 
2462754fe60SDimitry Andric     bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
247f22ef01cSRoman Divacky 
248f22ef01cSRoman Divacky     void InitCSEMap(MachineBasicBlock *BB);
249ffd1746dSEd Schouten 
250ffd1746dSEd Schouten     MachineBasicBlock *getCurPreheader();
251f22ef01cSRoman Divacky   };
2522cab237bSDimitry Andric 
2534ba319b5SDimitry Andric   class MachineLICM : public MachineLICMBase {
2544ba319b5SDimitry Andric   public:
2554ba319b5SDimitry Andric     static char ID;
MachineLICM()2564ba319b5SDimitry Andric     MachineLICM() : MachineLICMBase(ID, false) {
2574ba319b5SDimitry Andric       initializeMachineLICMPass(*PassRegistry::getPassRegistry());
2584ba319b5SDimitry Andric     }
2594ba319b5SDimitry Andric   };
2604ba319b5SDimitry Andric 
2614ba319b5SDimitry Andric   class EarlyMachineLICM : public MachineLICMBase {
2624ba319b5SDimitry Andric   public:
2634ba319b5SDimitry Andric     static char ID;
EarlyMachineLICM()2644ba319b5SDimitry Andric     EarlyMachineLICM() : MachineLICMBase(ID, true) {
2654ba319b5SDimitry Andric       initializeEarlyMachineLICMPass(*PassRegistry::getPassRegistry());
2664ba319b5SDimitry Andric     }
2674ba319b5SDimitry Andric   };
2684ba319b5SDimitry Andric 
269f22ef01cSRoman Divacky } // end anonymous namespace
270f22ef01cSRoman Divacky 
2714ba319b5SDimitry Andric char MachineLICM::ID;
2724ba319b5SDimitry Andric char EarlyMachineLICM::ID;
2732cab237bSDimitry Andric 
274dff0c46cSDimitry Andric char &llvm::MachineLICMID = MachineLICM::ID;
2754ba319b5SDimitry Andric char &llvm::EarlyMachineLICMID = EarlyMachineLICM::ID;
2762cab237bSDimitry Andric 
277302affcbSDimitry Andric INITIALIZE_PASS_BEGIN(MachineLICM, DEBUG_TYPE,
2782754fe60SDimitry Andric                       "Machine Loop Invariant Code Motion", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)2792754fe60SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
2802754fe60SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
2817d523365SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
282302affcbSDimitry Andric INITIALIZE_PASS_END(MachineLICM, DEBUG_TYPE,
2832754fe60SDimitry Andric                     "Machine Loop Invariant Code Motion", false, false)
284f22ef01cSRoman Divacky 
2854ba319b5SDimitry Andric INITIALIZE_PASS_BEGIN(EarlyMachineLICM, "early-machinelicm",
2864ba319b5SDimitry Andric                       "Early Machine Loop Invariant Code Motion", false, false)
2874ba319b5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
2884ba319b5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
2894ba319b5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2904ba319b5SDimitry Andric INITIALIZE_PASS_END(EarlyMachineLICM, "early-machinelicm",
2914ba319b5SDimitry Andric                     "Early Machine Loop Invariant Code Motion", false, false)
2924ba319b5SDimitry Andric 
2937d523365SDimitry Andric /// Test if the given loop is the outer-most loop that has a unique predecessor.
294ffd1746dSEd Schouten static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
295ffd1746dSEd Schouten   // Check whether this loop even has a unique predecessor.
296ffd1746dSEd Schouten   if (!CurLoop->getLoopPredecessor())
297f22ef01cSRoman Divacky     return false;
298ffd1746dSEd Schouten   // Ok, now check to see if any of its outer loops do.
299ffd1746dSEd Schouten   for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
300ffd1746dSEd Schouten     if (L->getLoopPredecessor())
301ffd1746dSEd Schouten       return false;
302ffd1746dSEd Schouten   // None of them did, so this is the outermost with a unique predecessor.
303f22ef01cSRoman Divacky   return true;
304f22ef01cSRoman Divacky }
305f22ef01cSRoman Divacky 
runOnMachineFunction(MachineFunction & MF)3064ba319b5SDimitry Andric bool MachineLICMBase::runOnMachineFunction(MachineFunction &MF) {
3072cab237bSDimitry Andric   if (skipFunction(MF.getFunction()))
30891bc56edSDimitry Andric     return false;
30991bc56edSDimitry Andric 
310ffd1746dSEd Schouten   Changed = FirstInLoop = false;
3118f0fd8f6SDimitry Andric   const TargetSubtargetInfo &ST = MF.getSubtarget();
3128f0fd8f6SDimitry Andric   TII = ST.getInstrInfo();
3138f0fd8f6SDimitry Andric   TLI = ST.getTargetLowering();
3148f0fd8f6SDimitry Andric   TRI = ST.getRegisterInfo();
315d88c1a5aSDimitry Andric   MFI = &MF.getFrameInfo();
3162754fe60SDimitry Andric   MRI = &MF.getRegInfo();
3174ba319b5SDimitry Andric   SchedModel.init(&ST);
318dff0c46cSDimitry Andric 
319dff0c46cSDimitry Andric   PreRegAlloc = MRI->isSSA();
320dff0c46cSDimitry Andric 
321dff0c46cSDimitry Andric   if (PreRegAlloc)
3224ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
323dff0c46cSDimitry Andric   else
3244ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
3254ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << MF.getName() << " ********\n");
326f22ef01cSRoman Divacky 
3272754fe60SDimitry Andric   if (PreRegAlloc) {
3282754fe60SDimitry Andric     // Estimate register pressure during pre-regalloc pass.
329ff0cc061SDimitry Andric     unsigned NumRPS = TRI->getNumRegPressureSets();
330ff0cc061SDimitry Andric     RegPressure.resize(NumRPS);
3312754fe60SDimitry Andric     std::fill(RegPressure.begin(), RegPressure.end(), 0);
332ff0cc061SDimitry Andric     RegLimit.resize(NumRPS);
333ff0cc061SDimitry Andric     for (unsigned i = 0, e = NumRPS; i != e; ++i)
334ff0cc061SDimitry Andric       RegLimit[i] = TRI->getRegPressureSetLimit(MF, i);
3352754fe60SDimitry Andric   }
3362754fe60SDimitry Andric 
337f22ef01cSRoman Divacky   // Get our Loop information...
338f22ef01cSRoman Divacky   MLI = &getAnalysis<MachineLoopInfo>();
339f22ef01cSRoman Divacky   DT  = &getAnalysis<MachineDominatorTree>();
3407d523365SDimitry Andric   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
341f22ef01cSRoman Divacky 
342ffd1746dSEd Schouten   SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
343ffd1746dSEd Schouten   while (!Worklist.empty()) {
344ffd1746dSEd Schouten     CurLoop = Worklist.pop_back_val();
34591bc56edSDimitry Andric     CurPreheader = nullptr;
346dff0c46cSDimitry Andric     ExitBlocks.clear();
347f22ef01cSRoman Divacky 
348f22ef01cSRoman Divacky     // If this is done before regalloc, only visit outer-most preheader-sporting
349f22ef01cSRoman Divacky     // loops.
350ffd1746dSEd Schouten     if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
351ffd1746dSEd Schouten       Worklist.append(CurLoop->begin(), CurLoop->end());
352f22ef01cSRoman Divacky       continue;
353ffd1746dSEd Schouten     }
354f22ef01cSRoman Divacky 
355dff0c46cSDimitry Andric     CurLoop->getExitBlocks(ExitBlocks);
356dff0c46cSDimitry Andric 
357f22ef01cSRoman Divacky     if (!PreRegAlloc)
358f22ef01cSRoman Divacky       HoistRegionPostRA();
359f22ef01cSRoman Divacky     else {
360f22ef01cSRoman Divacky       // CSEMap is initialized for loop header when the first instruction is
361f22ef01cSRoman Divacky       // being hoisted.
362f22ef01cSRoman Divacky       MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
363ffd1746dSEd Schouten       FirstInLoop = true;
364dff0c46cSDimitry Andric       HoistOutOfLoop(N);
365f22ef01cSRoman Divacky       CSEMap.clear();
366ff0cc061SDimitry Andric 
367ff0cc061SDimitry Andric       if (SinkInstsToAvoidSpills)
368ff0cc061SDimitry Andric         SinkIntoLoop();
369f22ef01cSRoman Divacky     }
370f22ef01cSRoman Divacky   }
371f22ef01cSRoman Divacky 
372f22ef01cSRoman Divacky   return Changed;
373f22ef01cSRoman Divacky }
374f22ef01cSRoman Divacky 
3757d523365SDimitry Andric /// Return true if instruction stores to the specified frame.
InstructionStoresToFI(const MachineInstr * MI,int FI)376f22ef01cSRoman Divacky static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
3774ba319b5SDimitry Andric   // Check mayStore before memory operands so that e.g. DBG_VALUEs will return
3784ba319b5SDimitry Andric   // true since they have no memory operands.
3794ba319b5SDimitry Andric   if (!MI->mayStore())
3804ba319b5SDimitry Andric      return false;
3817d523365SDimitry Andric   // If we lost memory operands, conservatively assume that the instruction
3827d523365SDimitry Andric   // writes to all slots.
3837d523365SDimitry Andric   if (MI->memoperands_empty())
3847d523365SDimitry Andric     return true;
385444ed5c5SDimitry Andric   for (const MachineMemOperand *MemOp : MI->memoperands()) {
386444ed5c5SDimitry Andric     if (!MemOp->isStore() || !MemOp->getPseudoValue())
387f22ef01cSRoman Divacky       continue;
388f22ef01cSRoman Divacky     if (const FixedStackPseudoSourceValue *Value =
389444ed5c5SDimitry Andric         dyn_cast<FixedStackPseudoSourceValue>(MemOp->getPseudoValue())) {
390f22ef01cSRoman Divacky       if (Value->getFrameIndex() == FI)
391f22ef01cSRoman Divacky         return true;
392f22ef01cSRoman Divacky     }
393f22ef01cSRoman Divacky   }
394f22ef01cSRoman Divacky   return false;
395f22ef01cSRoman Divacky }
396f22ef01cSRoman Divacky 
3977d523365SDimitry Andric /// Examine the instruction for potentai LICM candidate. Also
398f22ef01cSRoman Divacky /// gather register def and frame object update information.
ProcessMI(MachineInstr * MI,BitVector & PhysRegDefs,BitVector & PhysRegClobbers,SmallSet<int,32> & StoredFIs,SmallVectorImpl<CandidateInfo> & Candidates)3994ba319b5SDimitry Andric void MachineLICMBase::ProcessMI(MachineInstr *MI,
400dff0c46cSDimitry Andric                                 BitVector &PhysRegDefs,
401dff0c46cSDimitry Andric                                 BitVector &PhysRegClobbers,
402f22ef01cSRoman Divacky                                 SmallSet<int, 32> &StoredFIs,
403f785676fSDimitry Andric                                 SmallVectorImpl<CandidateInfo> &Candidates) {
404f22ef01cSRoman Divacky   bool RuledOut = false;
405f22ef01cSRoman Divacky   bool HasNonInvariantUse = false;
406f22ef01cSRoman Divacky   unsigned Def = 0;
407444ed5c5SDimitry Andric   for (const MachineOperand &MO : MI->operands()) {
408f22ef01cSRoman Divacky     if (MO.isFI()) {
409f22ef01cSRoman Divacky       // Remember if the instruction stores to the frame index.
410f22ef01cSRoman Divacky       int FI = MO.getIndex();
411f22ef01cSRoman Divacky       if (!StoredFIs.count(FI) &&
412f22ef01cSRoman Divacky           MFI->isSpillSlotObjectIndex(FI) &&
413f22ef01cSRoman Divacky           InstructionStoresToFI(MI, FI))
414f22ef01cSRoman Divacky         StoredFIs.insert(FI);
415f22ef01cSRoman Divacky       HasNonInvariantUse = true;
416f22ef01cSRoman Divacky       continue;
417f22ef01cSRoman Divacky     }
418f22ef01cSRoman Divacky 
419dff0c46cSDimitry Andric     // We can't hoist an instruction defining a physreg that is clobbered in
420dff0c46cSDimitry Andric     // the loop.
421dff0c46cSDimitry Andric     if (MO.isRegMask()) {
422dff0c46cSDimitry Andric       PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
423dff0c46cSDimitry Andric       continue;
424dff0c46cSDimitry Andric     }
425dff0c46cSDimitry Andric 
426f22ef01cSRoman Divacky     if (!MO.isReg())
427f22ef01cSRoman Divacky       continue;
428f22ef01cSRoman Divacky     unsigned Reg = MO.getReg();
429f22ef01cSRoman Divacky     if (!Reg)
430f22ef01cSRoman Divacky       continue;
431f22ef01cSRoman Divacky     assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
432f22ef01cSRoman Divacky            "Not expecting virtual register!");
433f22ef01cSRoman Divacky 
434f22ef01cSRoman Divacky     if (!MO.isDef()) {
435dff0c46cSDimitry Andric       if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
436f22ef01cSRoman Divacky         // If it's using a non-loop-invariant register, then it's obviously not
437f22ef01cSRoman Divacky         // safe to hoist.
438f22ef01cSRoman Divacky         HasNonInvariantUse = true;
439f22ef01cSRoman Divacky       continue;
440f22ef01cSRoman Divacky     }
441f22ef01cSRoman Divacky 
442f22ef01cSRoman Divacky     if (MO.isImplicit()) {
4437ae0e2c9SDimitry Andric       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
4447ae0e2c9SDimitry Andric         PhysRegClobbers.set(*AI);
445f22ef01cSRoman Divacky       if (!MO.isDead())
446f22ef01cSRoman Divacky         // Non-dead implicit def? This cannot be hoisted.
447f22ef01cSRoman Divacky         RuledOut = true;
448f22ef01cSRoman Divacky       // No need to check if a dead implicit def is also defined by
449f22ef01cSRoman Divacky       // another instruction.
450f22ef01cSRoman Divacky       continue;
451f22ef01cSRoman Divacky     }
452f22ef01cSRoman Divacky 
453f22ef01cSRoman Divacky     // FIXME: For now, avoid instructions with multiple defs, unless
454f22ef01cSRoman Divacky     // it's a dead implicit def.
455f22ef01cSRoman Divacky     if (Def)
456f22ef01cSRoman Divacky       RuledOut = true;
457f22ef01cSRoman Divacky     else
458f22ef01cSRoman Divacky       Def = Reg;
459f22ef01cSRoman Divacky 
460f22ef01cSRoman Divacky     // If we have already seen another instruction that defines the same
461dff0c46cSDimitry Andric     // register, then this is not safe.  Two defs is indicated by setting a
462dff0c46cSDimitry Andric     // PhysRegClobbers bit.
4637ae0e2c9SDimitry Andric     for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
464dff0c46cSDimitry Andric       if (PhysRegDefs.test(*AS))
465dff0c46cSDimitry Andric         PhysRegClobbers.set(*AS);
466f785676fSDimitry Andric     }
467*b5893f02SDimitry Andric     // Need a second loop because MCRegAliasIterator can visit the same
468*b5893f02SDimitry Andric     // register twice.
469*b5893f02SDimitry Andric     for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS)
470*b5893f02SDimitry Andric       PhysRegDefs.set(*AS);
471*b5893f02SDimitry Andric 
472f785676fSDimitry Andric     if (PhysRegClobbers.test(Reg))
473f22ef01cSRoman Divacky       // MI defined register is seen defined by another instruction in
474f22ef01cSRoman Divacky       // the loop, it cannot be a LICM candidate.
475f22ef01cSRoman Divacky       RuledOut = true;
476f22ef01cSRoman Divacky   }
477f22ef01cSRoman Divacky 
478f22ef01cSRoman Divacky   // Only consider reloads for now and remats which do not have register
479f22ef01cSRoman Divacky   // operands. FIXME: Consider unfold load folding instructions.
480f22ef01cSRoman Divacky   if (Def && !RuledOut) {
4812cab237bSDimitry Andric     int FI = std::numeric_limits<int>::min();
482f22ef01cSRoman Divacky     if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
4833ca95b02SDimitry Andric         (TII->isLoadFromStackSlot(*MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
484f22ef01cSRoman Divacky       Candidates.push_back(CandidateInfo(MI, Def, FI));
485f22ef01cSRoman Divacky   }
486f22ef01cSRoman Divacky }
487f22ef01cSRoman Divacky 
4887d523365SDimitry Andric /// Walk the specified region of the CFG and hoist loop invariants out to the
4897d523365SDimitry Andric /// preheader.
HoistRegionPostRA()4904ba319b5SDimitry Andric void MachineLICMBase::HoistRegionPostRA() {
491dff0c46cSDimitry Andric   MachineBasicBlock *Preheader = getCurPreheader();
492dff0c46cSDimitry Andric   if (!Preheader)
493dff0c46cSDimitry Andric     return;
494dff0c46cSDimitry Andric 
495f22ef01cSRoman Divacky   unsigned NumRegs = TRI->getNumRegs();
496dff0c46cSDimitry Andric   BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
497dff0c46cSDimitry Andric   BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
498f22ef01cSRoman Divacky 
499f22ef01cSRoman Divacky   SmallVector<CandidateInfo, 32> Candidates;
500f22ef01cSRoman Divacky   SmallSet<int, 32> StoredFIs;
501f22ef01cSRoman Divacky 
502f22ef01cSRoman Divacky   // Walk the entire region, count number of defs for each register, and
503f22ef01cSRoman Divacky   // collect potential LICM candidates.
504*b5893f02SDimitry Andric   for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
5056122f3e6SDimitry Andric     // If the header of the loop containing this basic block is a landing pad,
5066122f3e6SDimitry Andric     // then don't try to hoist instructions out of this loop.
5076122f3e6SDimitry Andric     const MachineLoop *ML = MLI->getLoopFor(BB);
5087d523365SDimitry Andric     if (ML && ML->getHeader()->isEHPad()) continue;
5096122f3e6SDimitry Andric 
510f22ef01cSRoman Divacky     // Conservatively treat live-in's as an external def.
511f22ef01cSRoman Divacky     // FIXME: That means a reload that're reused in successor block(s) will not
512f22ef01cSRoman Divacky     // be LICM'ed.
5137d523365SDimitry Andric     for (const auto &LI : BB->liveins()) {
5147d523365SDimitry Andric       for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI)
5157ae0e2c9SDimitry Andric         PhysRegDefs.set(*AI);
516f22ef01cSRoman Divacky     }
517f22ef01cSRoman Divacky 
5186122f3e6SDimitry Andric     SpeculationState = SpeculateUnknown;
519444ed5c5SDimitry Andric     for (MachineInstr &MI : *BB)
520444ed5c5SDimitry Andric       ProcessMI(&MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
521dff0c46cSDimitry Andric   }
522dff0c46cSDimitry Andric 
523dff0c46cSDimitry Andric   // Gather the registers read / clobbered by the terminator.
524dff0c46cSDimitry Andric   BitVector TermRegs(NumRegs);
525dff0c46cSDimitry Andric   MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
526dff0c46cSDimitry Andric   if (TI != Preheader->end()) {
527444ed5c5SDimitry Andric     for (const MachineOperand &MO : TI->operands()) {
528dff0c46cSDimitry Andric       if (!MO.isReg())
529dff0c46cSDimitry Andric         continue;
530dff0c46cSDimitry Andric       unsigned Reg = MO.getReg();
531dff0c46cSDimitry Andric       if (!Reg)
532dff0c46cSDimitry Andric         continue;
5337ae0e2c9SDimitry Andric       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
5347ae0e2c9SDimitry Andric         TermRegs.set(*AI);
535f22ef01cSRoman Divacky     }
536f22ef01cSRoman Divacky   }
537f22ef01cSRoman Divacky 
538f22ef01cSRoman Divacky   // Now evaluate whether the potential candidates qualify.
539f22ef01cSRoman Divacky   // 1. Check if the candidate defined register is defined by another
540f22ef01cSRoman Divacky   //    instruction in the loop.
541f22ef01cSRoman Divacky   // 2. If the candidate is a load from stack slot (always true for now),
542f22ef01cSRoman Divacky   //    check if the slot is stored anywhere in the loop.
543dff0c46cSDimitry Andric   // 3. Make sure candidate def should not clobber
544dff0c46cSDimitry Andric   //    registers read by the terminator. Similarly its def should not be
545dff0c46cSDimitry Andric   //    clobbered by the terminator.
546444ed5c5SDimitry Andric   for (CandidateInfo &Candidate : Candidates) {
5472cab237bSDimitry Andric     if (Candidate.FI != std::numeric_limits<int>::min() &&
548444ed5c5SDimitry Andric         StoredFIs.count(Candidate.FI))
549f22ef01cSRoman Divacky       continue;
550f22ef01cSRoman Divacky 
551444ed5c5SDimitry Andric     unsigned Def = Candidate.Def;
552dff0c46cSDimitry Andric     if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
553f22ef01cSRoman Divacky       bool Safe = true;
554444ed5c5SDimitry Andric       MachineInstr *MI = Candidate.MI;
555444ed5c5SDimitry Andric       for (const MachineOperand &MO : MI->operands()) {
556f22ef01cSRoman Divacky         if (!MO.isReg() || MO.isDef() || !MO.getReg())
557f22ef01cSRoman Divacky           continue;
558dff0c46cSDimitry Andric         unsigned Reg = MO.getReg();
559dff0c46cSDimitry Andric         if (PhysRegDefs.test(Reg) ||
560dff0c46cSDimitry Andric             PhysRegClobbers.test(Reg)) {
561f22ef01cSRoman Divacky           // If it's using a non-loop-invariant register, then it's obviously
562f22ef01cSRoman Divacky           // not safe to hoist.
563f22ef01cSRoman Divacky           Safe = false;
564f22ef01cSRoman Divacky           break;
565f22ef01cSRoman Divacky         }
566f22ef01cSRoman Divacky       }
567f22ef01cSRoman Divacky       if (Safe)
568444ed5c5SDimitry Andric         HoistPostRA(MI, Candidate.Def);
569f22ef01cSRoman Divacky     }
570f22ef01cSRoman Divacky   }
571f22ef01cSRoman Divacky }
572f22ef01cSRoman Divacky 
5737d523365SDimitry Andric /// Add register 'Reg' to the livein sets of BBs in the current loop, and make
5747d523365SDimitry Andric /// sure it is not killed by any instructions in the loop.
AddToLiveIns(unsigned Reg)5754ba319b5SDimitry Andric void MachineLICMBase::AddToLiveIns(unsigned Reg) {
576*b5893f02SDimitry Andric   for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
577f22ef01cSRoman Divacky     if (!BB->isLiveIn(Reg))
578f22ef01cSRoman Divacky       BB->addLiveIn(Reg);
579444ed5c5SDimitry Andric     for (MachineInstr &MI : *BB) {
580444ed5c5SDimitry Andric       for (MachineOperand &MO : MI.operands()) {
581f22ef01cSRoman Divacky         if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
582f22ef01cSRoman Divacky         if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
583f22ef01cSRoman Divacky           MO.setIsKill(false);
584f22ef01cSRoman Divacky       }
585f22ef01cSRoman Divacky     }
586f22ef01cSRoman Divacky   }
587f22ef01cSRoman Divacky }
588f22ef01cSRoman Divacky 
5897d523365SDimitry Andric /// When an instruction is found to only use loop invariant operands that is
5907d523365SDimitry Andric /// safe to hoist, this instruction is called to do the dirty work.
HoistPostRA(MachineInstr * MI,unsigned Def)5914ba319b5SDimitry Andric void MachineLICMBase::HoistPostRA(MachineInstr *MI, unsigned Def) {
592ffd1746dSEd Schouten   MachineBasicBlock *Preheader = getCurPreheader();
593ffd1746dSEd Schouten 
594f22ef01cSRoman Divacky   // Now move the instructions to the predecessor, inserting it before any
595f22ef01cSRoman Divacky   // terminator instructions.
5964ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Hoisting to " << printMBBReference(*Preheader)
5974ba319b5SDimitry Andric                     << " from " << printMBBReference(*MI->getParent()) << ": "
5984ba319b5SDimitry Andric                     << *MI);
599f22ef01cSRoman Divacky 
600f22ef01cSRoman Divacky   // Splice the instruction to the preheader.
601f22ef01cSRoman Divacky   MachineBasicBlock *MBB = MI->getParent();
602ffd1746dSEd Schouten   Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
603f22ef01cSRoman Divacky 
604f22ef01cSRoman Divacky   // Add register to livein list to all the BBs in the current loop since a
605f22ef01cSRoman Divacky   // loop invariant must be kept live throughout the whole loop. This is
606f22ef01cSRoman Divacky   // important to ensure later passes do not scavenge the def register.
607f22ef01cSRoman Divacky   AddToLiveIns(Def);
608f22ef01cSRoman Divacky 
609f22ef01cSRoman Divacky   ++NumPostRAHoisted;
610f22ef01cSRoman Divacky   Changed = true;
611f22ef01cSRoman Divacky }
612f22ef01cSRoman Divacky 
6137d523365SDimitry Andric /// Check if this mbb is guaranteed to execute. If not then a load from this mbb
6147d523365SDimitry Andric /// may not be safe to hoist.
IsGuaranteedToExecute(MachineBasicBlock * BB)6154ba319b5SDimitry Andric bool MachineLICMBase::IsGuaranteedToExecute(MachineBasicBlock *BB) {
6166122f3e6SDimitry Andric   if (SpeculationState != SpeculateUnknown)
6176122f3e6SDimitry Andric     return SpeculationState == SpeculateFalse;
6186122f3e6SDimitry Andric 
6196122f3e6SDimitry Andric   if (BB != CurLoop->getHeader()) {
6206122f3e6SDimitry Andric     // Check loop exiting blocks.
6216122f3e6SDimitry Andric     SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
6226122f3e6SDimitry Andric     CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
623444ed5c5SDimitry Andric     for (MachineBasicBlock *CurrentLoopExitingBlock : CurrentLoopExitingBlocks)
624444ed5c5SDimitry Andric       if (!DT->dominates(BB, CurrentLoopExitingBlock)) {
6256122f3e6SDimitry Andric         SpeculationState = SpeculateTrue;
6266122f3e6SDimitry Andric         return false;
6276122f3e6SDimitry Andric       }
6286122f3e6SDimitry Andric   }
6296122f3e6SDimitry Andric 
6306122f3e6SDimitry Andric   SpeculationState = SpeculateFalse;
6316122f3e6SDimitry Andric   return true;
6326122f3e6SDimitry Andric }
6336122f3e6SDimitry Andric 
EnterScope(MachineBasicBlock * MBB)6344ba319b5SDimitry Andric void MachineLICMBase::EnterScope(MachineBasicBlock *MBB) {
6354ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Entering " << printMBBReference(*MBB) << '\n');
636dff0c46cSDimitry Andric 
637dff0c46cSDimitry Andric   // Remember livein register pressure.
638dff0c46cSDimitry Andric   BackTrace.push_back(RegPressure);
639dff0c46cSDimitry Andric }
640dff0c46cSDimitry Andric 
ExitScope(MachineBasicBlock * MBB)6414ba319b5SDimitry Andric void MachineLICMBase::ExitScope(MachineBasicBlock *MBB) {
6424ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Exiting " << printMBBReference(*MBB) << '\n');
643dff0c46cSDimitry Andric   BackTrace.pop_back();
644dff0c46cSDimitry Andric }
645dff0c46cSDimitry Andric 
6467d523365SDimitry Andric /// Destroy scope for the MBB that corresponds to the given dominator tree node
6477d523365SDimitry Andric /// if its a leaf or all of its children are done. Walk up the dominator tree to
6487d523365SDimitry Andric /// destroy ancestors which are now done.
ExitScopeIfDone(MachineDomTreeNode * Node,DenseMap<MachineDomTreeNode *,unsigned> & OpenChildren,DenseMap<MachineDomTreeNode *,MachineDomTreeNode * > & ParentMap)6494ba319b5SDimitry Andric void MachineLICMBase::ExitScopeIfDone(MachineDomTreeNode *Node,
650dff0c46cSDimitry Andric     DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
651dff0c46cSDimitry Andric     DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
652dff0c46cSDimitry Andric   if (OpenChildren[Node])
653dff0c46cSDimitry Andric     return;
654dff0c46cSDimitry Andric 
655dff0c46cSDimitry Andric   // Pop scope.
656dff0c46cSDimitry Andric   ExitScope(Node->getBlock());
657dff0c46cSDimitry Andric 
658dff0c46cSDimitry Andric   // Now traverse upwards to pop ancestors whose offsprings are all done.
659dff0c46cSDimitry Andric   while (MachineDomTreeNode *Parent = ParentMap[Node]) {
660dff0c46cSDimitry Andric     unsigned Left = --OpenChildren[Parent];
661dff0c46cSDimitry Andric     if (Left != 0)
662dff0c46cSDimitry Andric       break;
663dff0c46cSDimitry Andric     ExitScope(Parent->getBlock());
664dff0c46cSDimitry Andric     Node = Parent;
665dff0c46cSDimitry Andric   }
666dff0c46cSDimitry Andric }
667dff0c46cSDimitry Andric 
6687d523365SDimitry Andric /// Walk the specified loop in the CFG (defined by all blocks dominated by the
6697d523365SDimitry Andric /// specified header block, and that are in the current loop) in depth first
6707d523365SDimitry Andric /// order w.r.t the DominatorTree. This allows us to visit definitions before
6717d523365SDimitry Andric /// uses, allowing us to hoist a loop body in one pass without iteration.
HoistOutOfLoop(MachineDomTreeNode * HeaderN)6724ba319b5SDimitry Andric void MachineLICMBase::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
673ff0cc061SDimitry Andric   MachineBasicBlock *Preheader = getCurPreheader();
674ff0cc061SDimitry Andric   if (!Preheader)
675ff0cc061SDimitry Andric     return;
676ff0cc061SDimitry Andric 
677dff0c46cSDimitry Andric   SmallVector<MachineDomTreeNode*, 32> Scopes;
678dff0c46cSDimitry Andric   SmallVector<MachineDomTreeNode*, 8> WorkList;
679dff0c46cSDimitry Andric   DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
680dff0c46cSDimitry Andric   DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
681dff0c46cSDimitry Andric 
682dff0c46cSDimitry Andric   // Perform a DFS walk to determine the order of visit.
683dff0c46cSDimitry Andric   WorkList.push_back(HeaderN);
684ff0cc061SDimitry Andric   while (!WorkList.empty()) {
685dff0c46cSDimitry Andric     MachineDomTreeNode *Node = WorkList.pop_back_val();
68691bc56edSDimitry Andric     assert(Node && "Null dominator tree node?");
687dff0c46cSDimitry Andric     MachineBasicBlock *BB = Node->getBlock();
688f22ef01cSRoman Divacky 
6896122f3e6SDimitry Andric     // If the header of the loop containing this basic block is a landing pad,
6906122f3e6SDimitry Andric     // then don't try to hoist instructions out of this loop.
6916122f3e6SDimitry Andric     const MachineLoop *ML = MLI->getLoopFor(BB);
6927d523365SDimitry Andric     if (ML && ML->getHeader()->isEHPad())
693dff0c46cSDimitry Andric       continue;
6946122f3e6SDimitry Andric 
695f22ef01cSRoman Divacky     // If this subregion is not in the top level loop at all, exit.
696dff0c46cSDimitry Andric     if (!CurLoop->contains(BB))
697dff0c46cSDimitry Andric       continue;
698f22ef01cSRoman Divacky 
699dff0c46cSDimitry Andric     Scopes.push_back(Node);
700dff0c46cSDimitry Andric     const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
701dff0c46cSDimitry Andric     unsigned NumChildren = Children.size();
702dff0c46cSDimitry Andric 
703dff0c46cSDimitry Andric     // Don't hoist things out of a large switch statement.  This often causes
704dff0c46cSDimitry Andric     // code to be hoisted that wasn't going to be executed, and increases
705dff0c46cSDimitry Andric     // register pressure in a situation where it's likely to matter.
706dff0c46cSDimitry Andric     if (BB->succ_size() >= 25)
707dff0c46cSDimitry Andric       NumChildren = 0;
708dff0c46cSDimitry Andric 
709dff0c46cSDimitry Andric     OpenChildren[Node] = NumChildren;
710dff0c46cSDimitry Andric     // Add children in reverse order as then the next popped worklist node is
711dff0c46cSDimitry Andric     // the first child of this node.  This means we ultimately traverse the
712dff0c46cSDimitry Andric     // DOM tree in exactly the same order as if we'd recursed.
713dff0c46cSDimitry Andric     for (int i = (int)NumChildren-1; i >= 0; --i) {
714dff0c46cSDimitry Andric       MachineDomTreeNode *Child = Children[i];
715dff0c46cSDimitry Andric       ParentMap[Child] = Node;
716dff0c46cSDimitry Andric       WorkList.push_back(Child);
717dff0c46cSDimitry Andric     }
718ff0cc061SDimitry Andric   }
719dff0c46cSDimitry Andric 
720ff0cc061SDimitry Andric   if (Scopes.size() == 0)
7212754fe60SDimitry Andric     return;
7222754fe60SDimitry Andric 
7232754fe60SDimitry Andric   // Compute registers which are livein into the loop headers.
7242754fe60SDimitry Andric   RegSeen.clear();
7252754fe60SDimitry Andric   BackTrace.clear();
7262754fe60SDimitry Andric   InitRegPressure(Preheader);
7272754fe60SDimitry Andric 
728dff0c46cSDimitry Andric   // Now perform LICM.
729444ed5c5SDimitry Andric   for (MachineDomTreeNode *Node : Scopes) {
730dff0c46cSDimitry Andric     MachineBasicBlock *MBB = Node->getBlock();
7312754fe60SDimitry Andric 
732dff0c46cSDimitry Andric     EnterScope(MBB);
733dff0c46cSDimitry Andric 
734dff0c46cSDimitry Andric     // Process the block
7356122f3e6SDimitry Andric     SpeculationState = SpeculateUnknown;
736f22ef01cSRoman Divacky     for (MachineBasicBlock::iterator
737dff0c46cSDimitry Andric          MII = MBB->begin(), E = MBB->end(); MII != E; ) {
738f22ef01cSRoman Divacky       MachineBasicBlock::iterator NextMII = MII; ++NextMII;
7392754fe60SDimitry Andric       MachineInstr *MI = &*MII;
7402754fe60SDimitry Andric       if (!Hoist(MI, Preheader))
7412754fe60SDimitry Andric         UpdateRegPressure(MI);
7424ba319b5SDimitry Andric       // If we have hoisted an instruction that may store, it can only be a
7434ba319b5SDimitry Andric       // constant store.
744f22ef01cSRoman Divacky       MII = NextMII;
745f22ef01cSRoman Divacky     }
746f22ef01cSRoman Divacky 
747dff0c46cSDimitry Andric     // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
748dff0c46cSDimitry Andric     ExitScopeIfDone(Node, OpenChildren, ParentMap);
749f22ef01cSRoman Divacky   }
7502754fe60SDimitry Andric }
7512754fe60SDimitry Andric 
7527d523365SDimitry Andric /// Sink instructions into loops if profitable. This especially tries to prevent
7537d523365SDimitry Andric /// register spills caused by register pressure if there is little to no
7547d523365SDimitry Andric /// overhead moving instructions into loops.
SinkIntoLoop()7554ba319b5SDimitry Andric void MachineLICMBase::SinkIntoLoop() {
756ff0cc061SDimitry Andric   MachineBasicBlock *Preheader = getCurPreheader();
757ff0cc061SDimitry Andric   if (!Preheader)
758ff0cc061SDimitry Andric     return;
759ff0cc061SDimitry Andric 
760ff0cc061SDimitry Andric   SmallVector<MachineInstr *, 8> Candidates;
761ff0cc061SDimitry Andric   for (MachineBasicBlock::instr_iterator I = Preheader->instr_begin();
762ff0cc061SDimitry Andric        I != Preheader->instr_end(); ++I) {
763ff0cc061SDimitry Andric     // We need to ensure that we can safely move this instruction into the loop.
764ff0cc061SDimitry Andric     // As such, it must not have side-effects, e.g. such as a call has.
7657d523365SDimitry Andric     if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(&*I))
7667d523365SDimitry Andric       Candidates.push_back(&*I);
7672754fe60SDimitry Andric   }
7682754fe60SDimitry Andric 
769ff0cc061SDimitry Andric   for (MachineInstr *I : Candidates) {
770ff0cc061SDimitry Andric     const MachineOperand &MO = I->getOperand(0);
771ff0cc061SDimitry Andric     if (!MO.isDef() || !MO.isReg() || !MO.getReg())
772ff0cc061SDimitry Andric       continue;
773ff0cc061SDimitry Andric     if (!MRI->hasOneDef(MO.getReg()))
774ff0cc061SDimitry Andric       continue;
775ff0cc061SDimitry Andric     bool CanSink = true;
776ff0cc061SDimitry Andric     MachineBasicBlock *B = nullptr;
777ff0cc061SDimitry Andric     for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
778ff0cc061SDimitry Andric       // FIXME: Come up with a proper cost model that estimates whether sinking
779ff0cc061SDimitry Andric       // the instruction (and thus possibly executing it on every loop
780ff0cc061SDimitry Andric       // iteration) is more expensive than a register.
781ff0cc061SDimitry Andric       // For now assumes that copies are cheap and thus almost always worth it.
782ff0cc061SDimitry Andric       if (!MI.isCopy()) {
783ff0cc061SDimitry Andric         CanSink = false;
784ff0cc061SDimitry Andric         break;
7856122f3e6SDimitry Andric       }
786ff0cc061SDimitry Andric       if (!B) {
787ff0cc061SDimitry Andric         B = MI.getParent();
788ff0cc061SDimitry Andric         continue;
789ff0cc061SDimitry Andric       }
790ff0cc061SDimitry Andric       B = DT->findNearestCommonDominator(B, MI.getParent());
791ff0cc061SDimitry Andric       if (!B) {
792ff0cc061SDimitry Andric         CanSink = false;
793ff0cc061SDimitry Andric         break;
794ff0cc061SDimitry Andric       }
795ff0cc061SDimitry Andric     }
796ff0cc061SDimitry Andric     if (!CanSink || !B || B == Preheader)
797ff0cc061SDimitry Andric       continue;
798ff0cc061SDimitry Andric     B->splice(B->getFirstNonPHI(), Preheader, I);
799ff0cc061SDimitry Andric   }
800ff0cc061SDimitry Andric }
801ff0cc061SDimitry Andric 
isOperandKill(const MachineOperand & MO,MachineRegisterInfo * MRI)802ff0cc061SDimitry Andric static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
803ff0cc061SDimitry Andric   return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
8046122f3e6SDimitry Andric }
8056122f3e6SDimitry Andric 
8067d523365SDimitry Andric /// Find all virtual register references that are liveout of the preheader to
8077d523365SDimitry Andric /// initialize the starting "register pressure". Note this does not count live
8087d523365SDimitry Andric /// through (livein but not used) registers.
InitRegPressure(MachineBasicBlock * BB)8094ba319b5SDimitry Andric void MachineLICMBase::InitRegPressure(MachineBasicBlock *BB) {
8102754fe60SDimitry Andric   std::fill(RegPressure.begin(), RegPressure.end(), 0);
8112754fe60SDimitry Andric 
8122754fe60SDimitry Andric   // If the preheader has only a single predecessor and it ends with a
8132754fe60SDimitry Andric   // fallthrough or an unconditional branch, then scan its predecessor for live
8142754fe60SDimitry Andric   // defs as well. This happens whenever the preheader is created by splitting
8152754fe60SDimitry Andric   // the critical edge from the loop predecessor to the loop header.
8162754fe60SDimitry Andric   if (BB->pred_size() == 1) {
81791bc56edSDimitry Andric     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
8182754fe60SDimitry Andric     SmallVector<MachineOperand, 4> Cond;
8193ca95b02SDimitry Andric     if (!TII->analyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
8202754fe60SDimitry Andric       InitRegPressure(*BB->pred_begin());
8212754fe60SDimitry Andric   }
8222754fe60SDimitry Andric 
823ff0cc061SDimitry Andric   for (const MachineInstr &MI : *BB)
824ff0cc061SDimitry Andric     UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
8252754fe60SDimitry Andric }
8262754fe60SDimitry Andric 
8277d523365SDimitry Andric /// Update estimate of register pressure after the specified instruction.
UpdateRegPressure(const MachineInstr * MI,bool ConsiderUnseenAsDef)8284ba319b5SDimitry Andric void MachineLICMBase::UpdateRegPressure(const MachineInstr *MI,
829ff0cc061SDimitry Andric                                         bool ConsiderUnseenAsDef) {
830ff0cc061SDimitry Andric   auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
831ff0cc061SDimitry Andric   for (const auto &RPIdAndCost : Cost) {
832ff0cc061SDimitry Andric     unsigned Class = RPIdAndCost.first;
833ff0cc061SDimitry Andric     if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second)
834ff0cc061SDimitry Andric       RegPressure[Class] = 0;
835ff0cc061SDimitry Andric     else
836ff0cc061SDimitry Andric       RegPressure[Class] += RPIdAndCost.second;
837ff0cc061SDimitry Andric   }
838ff0cc061SDimitry Andric }
8392754fe60SDimitry Andric 
8407d523365SDimitry Andric /// Calculate the additional register pressure that the registers used in MI
8417d523365SDimitry Andric /// cause.
8427d523365SDimitry Andric ///
8437d523365SDimitry Andric /// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
8447d523365SDimitry Andric /// figure out which usages are live-ins.
8457d523365SDimitry Andric /// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
846ff0cc061SDimitry Andric DenseMap<unsigned, int>
calcRegisterCost(const MachineInstr * MI,bool ConsiderSeen,bool ConsiderUnseenAsDef)8474ba319b5SDimitry Andric MachineLICMBase::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
848ff0cc061SDimitry Andric                                   bool ConsiderUnseenAsDef) {
849ff0cc061SDimitry Andric   DenseMap<unsigned, int> Cost;
850ff0cc061SDimitry Andric   if (MI->isImplicitDef())
851ff0cc061SDimitry Andric     return Cost;
8522754fe60SDimitry Andric   for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
8532754fe60SDimitry Andric     const MachineOperand &MO = MI->getOperand(i);
8542754fe60SDimitry Andric     if (!MO.isReg() || MO.isImplicit())
8552754fe60SDimitry Andric       continue;
8562754fe60SDimitry Andric     unsigned Reg = MO.getReg();
8572754fe60SDimitry Andric     if (!TargetRegisterInfo::isVirtualRegister(Reg))
8582754fe60SDimitry Andric       continue;
8592754fe60SDimitry Andric 
860ff0cc061SDimitry Andric     // FIXME: It seems bad to use RegSeen only for some of these calculations.
861ff0cc061SDimitry Andric     bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
862ff0cc061SDimitry Andric     const TargetRegisterClass *RC = MRI->getRegClass(Reg);
8632754fe60SDimitry Andric 
864ff0cc061SDimitry Andric     RegClassWeight W = TRI->getRegClassWeight(RC);
865ff0cc061SDimitry Andric     int RCCost = 0;
866ff0cc061SDimitry Andric     if (MO.isDef())
867ff0cc061SDimitry Andric       RCCost = W.RegWeight;
868ff0cc061SDimitry Andric     else {
869ff0cc061SDimitry Andric       bool isKill = isOperandKill(MO, MRI);
870ff0cc061SDimitry Andric       if (isNew && !isKill && ConsiderUnseenAsDef)
871ff0cc061SDimitry Andric         // Haven't seen this, it must be a livein.
872ff0cc061SDimitry Andric         RCCost = W.RegWeight;
873ff0cc061SDimitry Andric       else if (!isNew && isKill)
874ff0cc061SDimitry Andric         RCCost = -W.RegWeight;
8752754fe60SDimitry Andric     }
876ff0cc061SDimitry Andric     if (RCCost == 0)
877ff0cc061SDimitry Andric       continue;
878ff0cc061SDimitry Andric     const int *PS = TRI->getRegClassPressureSets(RC);
879ff0cc061SDimitry Andric     for (; *PS != -1; ++PS) {
880ff0cc061SDimitry Andric       if (Cost.find(*PS) == Cost.end())
881ff0cc061SDimitry Andric         Cost[*PS] = RCCost;
882ff0cc061SDimitry Andric       else
883ff0cc061SDimitry Andric         Cost[*PS] += RCCost;
884ff0cc061SDimitry Andric     }
885ff0cc061SDimitry Andric   }
886ff0cc061SDimitry Andric   return Cost;
887e580952dSDimitry Andric }
888f22ef01cSRoman Divacky 
8897d523365SDimitry Andric /// Return true if this machine instruction loads from global offset table or
8907d523365SDimitry Andric /// constant pool.
mayLoadFromGOTOrConstantPool(MachineInstr & MI)8917d523365SDimitry Andric static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
892dff0c46cSDimitry Andric   assert(MI.mayLoad() && "Expected MI that loads!");
8937d523365SDimitry Andric 
8947d523365SDimitry Andric   // If we lost memory operands, conservatively assume that the instruction
8957d523365SDimitry Andric   // reads from everything..
8967d523365SDimitry Andric   if (MI.memoperands_empty())
8977d523365SDimitry Andric     return true;
8987d523365SDimitry Andric 
899444ed5c5SDimitry Andric   for (MachineMemOperand *MemOp : MI.memoperands())
900444ed5c5SDimitry Andric     if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
9017d523365SDimitry Andric       if (PSV->isGOT() || PSV->isConstantPool())
902dff0c46cSDimitry Andric         return true;
903444ed5c5SDimitry Andric 
904dff0c46cSDimitry Andric   return false;
905dff0c46cSDimitry Andric }
906dff0c46cSDimitry Andric 
9074ba319b5SDimitry Andric // This function iterates through all the operands of the input store MI and
9084ba319b5SDimitry Andric // checks that each register operand statisfies isCallerPreservedPhysReg.
9094ba319b5SDimitry Andric // This means, the value being stored and the address where it is being stored
9104ba319b5SDimitry Andric // is constant throughout the body of the function (not including prologue and
9114ba319b5SDimitry Andric // epilogue). When called with an MI that isn't a store, it returns false.
9124ba319b5SDimitry Andric // A future improvement can be to check if the store registers are constant
9134ba319b5SDimitry Andric // throughout the loop rather than throughout the funtion.
isInvariantStore(const MachineInstr & MI,const TargetRegisterInfo * TRI,const MachineRegisterInfo * MRI)9144ba319b5SDimitry Andric static bool isInvariantStore(const MachineInstr &MI,
9154ba319b5SDimitry Andric                              const TargetRegisterInfo *TRI,
9164ba319b5SDimitry Andric                              const MachineRegisterInfo *MRI) {
9174ba319b5SDimitry Andric 
9184ba319b5SDimitry Andric   bool FoundCallerPresReg = false;
9194ba319b5SDimitry Andric   if (!MI.mayStore() || MI.hasUnmodeledSideEffects() ||
9204ba319b5SDimitry Andric       (MI.getNumOperands() == 0))
9214ba319b5SDimitry Andric     return false;
9224ba319b5SDimitry Andric 
9234ba319b5SDimitry Andric   // Check that all register operands are caller-preserved physical registers.
9244ba319b5SDimitry Andric   for (const MachineOperand &MO : MI.operands()) {
9254ba319b5SDimitry Andric     if (MO.isReg()) {
9264ba319b5SDimitry Andric       unsigned Reg = MO.getReg();
9274ba319b5SDimitry Andric       // If operand is a virtual register, check if it comes from a copy of a
9284ba319b5SDimitry Andric       // physical register.
9294ba319b5SDimitry Andric       if (TargetRegisterInfo::isVirtualRegister(Reg))
9304ba319b5SDimitry Andric         Reg = TRI->lookThruCopyLike(MO.getReg(), MRI);
9314ba319b5SDimitry Andric       if (TargetRegisterInfo::isVirtualRegister(Reg))
9324ba319b5SDimitry Andric         return false;
9334ba319b5SDimitry Andric       if (!TRI->isCallerPreservedPhysReg(Reg, *MI.getMF()))
9344ba319b5SDimitry Andric         return false;
9354ba319b5SDimitry Andric       else
9364ba319b5SDimitry Andric         FoundCallerPresReg = true;
9374ba319b5SDimitry Andric     } else if (!MO.isImm()) {
9384ba319b5SDimitry Andric         return false;
9394ba319b5SDimitry Andric     }
9404ba319b5SDimitry Andric   }
9414ba319b5SDimitry Andric   return FoundCallerPresReg;
9424ba319b5SDimitry Andric }
9434ba319b5SDimitry Andric 
9444ba319b5SDimitry Andric // Return true if the input MI is a copy instruction that feeds an invariant
9454ba319b5SDimitry Andric // store instruction. This means that the src of the copy has to satisfy
9464ba319b5SDimitry Andric // isCallerPreservedPhysReg and atleast one of it's users should satisfy
9474ba319b5SDimitry Andric // isInvariantStore.
isCopyFeedingInvariantStore(const MachineInstr & MI,const MachineRegisterInfo * MRI,const TargetRegisterInfo * TRI)9484ba319b5SDimitry Andric static bool isCopyFeedingInvariantStore(const MachineInstr &MI,
9494ba319b5SDimitry Andric                                         const MachineRegisterInfo *MRI,
9504ba319b5SDimitry Andric                                         const TargetRegisterInfo *TRI) {
9514ba319b5SDimitry Andric 
9524ba319b5SDimitry Andric   // FIXME: If targets would like to look through instructions that aren't
9534ba319b5SDimitry Andric   // pure copies, this can be updated to a query.
9544ba319b5SDimitry Andric   if (!MI.isCopy())
9554ba319b5SDimitry Andric     return false;
9564ba319b5SDimitry Andric 
9574ba319b5SDimitry Andric   const MachineFunction *MF = MI.getMF();
9584ba319b5SDimitry Andric   // Check that we are copying a constant physical register.
9594ba319b5SDimitry Andric   unsigned CopySrcReg = MI.getOperand(1).getReg();
9604ba319b5SDimitry Andric   if (TargetRegisterInfo::isVirtualRegister(CopySrcReg))
9614ba319b5SDimitry Andric     return false;
9624ba319b5SDimitry Andric 
9634ba319b5SDimitry Andric   if (!TRI->isCallerPreservedPhysReg(CopySrcReg, *MF))
9644ba319b5SDimitry Andric     return false;
9654ba319b5SDimitry Andric 
9664ba319b5SDimitry Andric   unsigned CopyDstReg = MI.getOperand(0).getReg();
9674ba319b5SDimitry Andric   // Check if any of the uses of the copy are invariant stores.
9684ba319b5SDimitry Andric   assert (TargetRegisterInfo::isVirtualRegister(CopyDstReg) &&
9694ba319b5SDimitry Andric           "copy dst is not a virtual reg");
9704ba319b5SDimitry Andric 
9714ba319b5SDimitry Andric   for (MachineInstr &UseMI : MRI->use_instructions(CopyDstReg)) {
9724ba319b5SDimitry Andric     if (UseMI.mayStore() && isInvariantStore(UseMI, TRI, MRI))
9734ba319b5SDimitry Andric       return true;
9744ba319b5SDimitry Andric   }
9754ba319b5SDimitry Andric   return false;
9764ba319b5SDimitry Andric }
9774ba319b5SDimitry Andric 
9787d523365SDimitry Andric /// Returns true if the instruction may be a suitable candidate for LICM.
9797d523365SDimitry Andric /// e.g. If the instruction is a call, then it's obviously not safe to hoist it.
IsLICMCandidate(MachineInstr & I)9804ba319b5SDimitry Andric bool MachineLICMBase::IsLICMCandidate(MachineInstr &I) {
981ffd1746dSEd Schouten   // Check if it's safe to move the instruction.
982ffd1746dSEd Schouten   bool DontMoveAcrossStore = true;
9834ba319b5SDimitry Andric   if ((!I.isSafeToMove(AA, DontMoveAcrossStore)) &&
9844ba319b5SDimitry Andric       !(HoistConstStores && isInvariantStore(I, TRI, MRI))) {
985f22ef01cSRoman Divacky     return false;
9864ba319b5SDimitry Andric   }
987f22ef01cSRoman Divacky 
9886122f3e6SDimitry Andric   // If it is load then check if it is guaranteed to execute by making sure that
9896122f3e6SDimitry Andric   // it dominates all exiting blocks. If it doesn't, then there is a path out of
990dff0c46cSDimitry Andric   // the loop which does not execute this load, so we can't hoist it. Loads
991dff0c46cSDimitry Andric   // from constant memory are not safe to speculate all the time, for example
992dff0c46cSDimitry Andric   // indexed load from a jump table.
9936122f3e6SDimitry Andric   // Stores and side effects are already checked by isSafeToMove.
9947d523365SDimitry Andric   if (I.mayLoad() && !mayLoadFromGOTOrConstantPool(I) &&
995dff0c46cSDimitry Andric       !IsGuaranteedToExecute(I.getParent()))
9966122f3e6SDimitry Andric     return false;
9976122f3e6SDimitry Andric 
998f22ef01cSRoman Divacky   return true;
999f22ef01cSRoman Divacky }
1000f22ef01cSRoman Divacky 
10017d523365SDimitry Andric /// Returns true if the instruction is loop invariant.
10027d523365SDimitry Andric /// I.e., all virtual register operands are defined outside of the loop,
10037d523365SDimitry Andric /// physical registers aren't accessed explicitly, and there are no side
1004f22ef01cSRoman Divacky /// effects that aren't captured by the operands or other flags.
IsLoopInvariantInst(MachineInstr & I)10054ba319b5SDimitry Andric bool MachineLICMBase::IsLoopInvariantInst(MachineInstr &I) {
1006f22ef01cSRoman Divacky   if (!IsLICMCandidate(I))
1007f22ef01cSRoman Divacky     return false;
1008f22ef01cSRoman Divacky 
1009f22ef01cSRoman Divacky   // The instruction is loop invariant if all of its operands are.
1010444ed5c5SDimitry Andric   for (const MachineOperand &MO : I.operands()) {
1011f22ef01cSRoman Divacky     if (!MO.isReg())
1012f22ef01cSRoman Divacky       continue;
1013f22ef01cSRoman Divacky 
1014f22ef01cSRoman Divacky     unsigned Reg = MO.getReg();
1015f22ef01cSRoman Divacky     if (Reg == 0) continue;
1016f22ef01cSRoman Divacky 
1017f22ef01cSRoman Divacky     // Don't hoist an instruction that uses or defines a physical register.
1018f22ef01cSRoman Divacky     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1019f22ef01cSRoman Divacky       if (MO.isUse()) {
1020f22ef01cSRoman Divacky         // If the physreg has no defs anywhere, it's just an ambient register
1021f22ef01cSRoman Divacky         // and we can freely move its uses. Alternatively, if it's allocatable,
1022f22ef01cSRoman Divacky         // it could get allocated to something with a def during allocation.
102324d58133SDimitry Andric         // However, if the physreg is known to always be caller saved/restored
102424d58133SDimitry Andric         // then this use is safe to hoist.
102524d58133SDimitry Andric         if (!MRI->isConstantPhysReg(Reg) &&
10262cab237bSDimitry Andric             !(TRI->isCallerPreservedPhysReg(Reg, *I.getMF())))
1027f22ef01cSRoman Divacky           return false;
1028f22ef01cSRoman Divacky         // Otherwise it's safe to move.
1029f22ef01cSRoman Divacky         continue;
1030f22ef01cSRoman Divacky       } else if (!MO.isDead()) {
1031f22ef01cSRoman Divacky         // A def that isn't dead. We can't move it.
1032f22ef01cSRoman Divacky         return false;
1033f22ef01cSRoman Divacky       } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
1034f22ef01cSRoman Divacky         // If the reg is live into the loop, we can't hoist an instruction
1035f22ef01cSRoman Divacky         // which would clobber it.
1036f22ef01cSRoman Divacky         return false;
1037f22ef01cSRoman Divacky       }
1038f22ef01cSRoman Divacky     }
1039f22ef01cSRoman Divacky 
1040f22ef01cSRoman Divacky     if (!MO.isUse())
1041f22ef01cSRoman Divacky       continue;
1042f22ef01cSRoman Divacky 
10432754fe60SDimitry Andric     assert(MRI->getVRegDef(Reg) &&
1044f22ef01cSRoman Divacky            "Machine instr not mapped for this vreg?!");
1045f22ef01cSRoman Divacky 
1046f22ef01cSRoman Divacky     // If the loop contains the definition of an operand, then the instruction
1047f22ef01cSRoman Divacky     // isn't loop invariant.
10482754fe60SDimitry Andric     if (CurLoop->contains(MRI->getVRegDef(Reg)))
1049f22ef01cSRoman Divacky       return false;
1050f22ef01cSRoman Divacky   }
1051f22ef01cSRoman Divacky 
1052f22ef01cSRoman Divacky   // If we got this far, the instruction is loop invariant!
1053f22ef01cSRoman Divacky   return true;
1054f22ef01cSRoman Divacky }
1055f22ef01cSRoman Divacky 
10567d523365SDimitry Andric /// Return true if the specified instruction is used by a phi node and hoisting
10577d523365SDimitry Andric /// it could cause a copy to be inserted.
HasLoopPHIUse(const MachineInstr * MI) const10584ba319b5SDimitry Andric bool MachineLICMBase::HasLoopPHIUse(const MachineInstr *MI) const {
1059dff0c46cSDimitry Andric   SmallVector<const MachineInstr*, 8> Work(1, MI);
1060dff0c46cSDimitry Andric   do {
1061dff0c46cSDimitry Andric     MI = Work.pop_back_val();
106297bc6c73SDimitry Andric     for (const MachineOperand &MO : MI->operands()) {
106397bc6c73SDimitry Andric       if (!MO.isReg() || !MO.isDef())
1064dff0c46cSDimitry Andric         continue;
106597bc6c73SDimitry Andric       unsigned Reg = MO.getReg();
1066dff0c46cSDimitry Andric       if (!TargetRegisterInfo::isVirtualRegister(Reg))
1067dff0c46cSDimitry Andric         continue;
106891bc56edSDimitry Andric       for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
1069dff0c46cSDimitry Andric         // A PHI may cause a copy to be inserted.
107091bc56edSDimitry Andric         if (UseMI.isPHI()) {
1071dff0c46cSDimitry Andric           // A PHI inside the loop causes a copy because the live range of Reg is
1072dff0c46cSDimitry Andric           // extended across the PHI.
107391bc56edSDimitry Andric           if (CurLoop->contains(&UseMI))
1074f22ef01cSRoman Divacky             return true;
1075dff0c46cSDimitry Andric           // A PHI in an exit block can cause a copy to be inserted if the PHI
1076dff0c46cSDimitry Andric           // has multiple predecessors in the loop with different values.
1077dff0c46cSDimitry Andric           // For now, approximate by rejecting all exit blocks.
107891bc56edSDimitry Andric           if (isExitBlock(UseMI.getParent()))
10793b0f4066SDimitry Andric             return true;
1080dff0c46cSDimitry Andric           continue;
1081dff0c46cSDimitry Andric         }
1082dff0c46cSDimitry Andric         // Look past copies as well.
108391bc56edSDimitry Andric         if (UseMI.isCopy() && CurLoop->contains(&UseMI))
108491bc56edSDimitry Andric           Work.push_back(&UseMI);
10853b0f4066SDimitry Andric       }
1086f22ef01cSRoman Divacky     }
1087dff0c46cSDimitry Andric   } while (!Work.empty());
1088f22ef01cSRoman Divacky   return false;
1089f22ef01cSRoman Divacky }
1090f22ef01cSRoman Divacky 
10917d523365SDimitry Andric /// Compute operand latency between a def of 'Reg' and an use in the current
10927d523365SDimitry Andric /// loop, return true if the target considered it high.
HasHighOperandLatency(MachineInstr & MI,unsigned DefIdx,unsigned Reg) const10934ba319b5SDimitry Andric bool MachineLICMBase::HasHighOperandLatency(MachineInstr &MI,
10944ba319b5SDimitry Andric                                             unsigned DefIdx,
10954ba319b5SDimitry Andric                                             unsigned Reg) const {
10968f0fd8f6SDimitry Andric   if (MRI->use_nodbg_empty(Reg))
10972754fe60SDimitry Andric     return false;
10982754fe60SDimitry Andric 
109991bc56edSDimitry Andric   for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
110091bc56edSDimitry Andric     if (UseMI.isCopyLike())
11012754fe60SDimitry Andric       continue;
110291bc56edSDimitry Andric     if (!CurLoop->contains(UseMI.getParent()))
11032754fe60SDimitry Andric       continue;
110491bc56edSDimitry Andric     for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
110591bc56edSDimitry Andric       const MachineOperand &MO = UseMI.getOperand(i);
11062754fe60SDimitry Andric       if (!MO.isReg() || !MO.isUse())
11072754fe60SDimitry Andric         continue;
11082754fe60SDimitry Andric       unsigned MOReg = MO.getReg();
11092754fe60SDimitry Andric       if (MOReg != Reg)
11102754fe60SDimitry Andric         continue;
11112754fe60SDimitry Andric 
11123ca95b02SDimitry Andric       if (TII->hasHighOperandLatency(SchedModel, MRI, MI, DefIdx, UseMI, i))
11132754fe60SDimitry Andric         return true;
11142754fe60SDimitry Andric     }
11152754fe60SDimitry Andric 
11162754fe60SDimitry Andric     // Only look at the first in loop use.
11172754fe60SDimitry Andric     break;
11182754fe60SDimitry Andric   }
11192754fe60SDimitry Andric 
11202754fe60SDimitry Andric   return false;
11212754fe60SDimitry Andric }
11222754fe60SDimitry Andric 
11237d523365SDimitry Andric /// Return true if the instruction is marked "cheap" or the operand latency
11247d523365SDimitry Andric /// between its def and a use is one or less.
IsCheapInstruction(MachineInstr & MI) const11254ba319b5SDimitry Andric bool MachineLICMBase::IsCheapInstruction(MachineInstr &MI) const {
11263ca95b02SDimitry Andric   if (TII->isAsCheapAsAMove(MI) || MI.isCopyLike())
11272754fe60SDimitry Andric     return true;
11282754fe60SDimitry Andric 
11292754fe60SDimitry Andric   bool isCheap = false;
11302754fe60SDimitry Andric   unsigned NumDefs = MI.getDesc().getNumDefs();
11312754fe60SDimitry Andric   for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
11322754fe60SDimitry Andric     MachineOperand &DefMO = MI.getOperand(i);
11332754fe60SDimitry Andric     if (!DefMO.isReg() || !DefMO.isDef())
11342754fe60SDimitry Andric       continue;
11352754fe60SDimitry Andric     --NumDefs;
11362754fe60SDimitry Andric     unsigned Reg = DefMO.getReg();
11372754fe60SDimitry Andric     if (TargetRegisterInfo::isPhysicalRegister(Reg))
11382754fe60SDimitry Andric       continue;
11392754fe60SDimitry Andric 
11403ca95b02SDimitry Andric     if (!TII->hasLowDefLatency(SchedModel, MI, i))
11412754fe60SDimitry Andric       return false;
11422754fe60SDimitry Andric     isCheap = true;
11432754fe60SDimitry Andric   }
11442754fe60SDimitry Andric 
11452754fe60SDimitry Andric   return isCheap;
11462754fe60SDimitry Andric }
11472754fe60SDimitry Andric 
11487d523365SDimitry Andric /// Visit BBs from header to current BB, check if hoisting an instruction of the
11497d523365SDimitry Andric /// given cost matrix can cause high register pressure.
11504ba319b5SDimitry Andric bool
CanCauseHighRegPressure(const DenseMap<unsigned,int> & Cost,bool CheapInstr)11514ba319b5SDimitry Andric MachineLICMBase::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
1152dff0c46cSDimitry Andric                                          bool CheapInstr) {
1153ff0cc061SDimitry Andric   for (const auto &RPIdAndCost : Cost) {
1154ff0cc061SDimitry Andric     if (RPIdAndCost.second <= 0)
11552754fe60SDimitry Andric       continue;
11562754fe60SDimitry Andric 
1157ff0cc061SDimitry Andric     unsigned Class = RPIdAndCost.first;
1158ff0cc061SDimitry Andric     int Limit = RegLimit[Class];
1159dff0c46cSDimitry Andric 
1160dff0c46cSDimitry Andric     // Don't hoist cheap instructions if they would increase register pressure,
1161dff0c46cSDimitry Andric     // even if we're under the limit.
116239d628a0SDimitry Andric     if (CheapInstr && !HoistCheapInsts)
1163dff0c46cSDimitry Andric       return true;
1164dff0c46cSDimitry Andric 
1165ff0cc061SDimitry Andric     for (const auto &RP : BackTrace)
1166ff0cc061SDimitry Andric       if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit)
11672754fe60SDimitry Andric         return true;
11682754fe60SDimitry Andric   }
11692754fe60SDimitry Andric 
11702754fe60SDimitry Andric   return false;
11712754fe60SDimitry Andric }
11722754fe60SDimitry Andric 
11737d523365SDimitry Andric /// Traverse the back trace from header to the current block and update their
11747d523365SDimitry Andric /// register pressures to reflect the effect of hoisting MI from the current
11757d523365SDimitry Andric /// block to the preheader.
UpdateBackTraceRegPressure(const MachineInstr * MI)11764ba319b5SDimitry Andric void MachineLICMBase::UpdateBackTraceRegPressure(const MachineInstr *MI) {
11772754fe60SDimitry Andric   // First compute the 'cost' of the instruction, i.e. its contribution
11782754fe60SDimitry Andric   // to register pressure.
1179ff0cc061SDimitry Andric   auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
1180ff0cc061SDimitry Andric                                /*ConsiderUnseenAsDef=*/false);
11812754fe60SDimitry Andric 
11822754fe60SDimitry Andric   // Update register pressure of blocks from loop header to current block.
1183ff0cc061SDimitry Andric   for (auto &RP : BackTrace)
1184ff0cc061SDimitry Andric     for (const auto &RPIdAndCost : Cost)
1185ff0cc061SDimitry Andric       RP[RPIdAndCost.first] += RPIdAndCost.second;
1186f22ef01cSRoman Divacky }
1187f22ef01cSRoman Divacky 
11887d523365SDimitry Andric /// Return true if it is potentially profitable to hoist the given loop
11897d523365SDimitry Andric /// invariant.
IsProfitableToHoist(MachineInstr & MI)11904ba319b5SDimitry Andric bool MachineLICMBase::IsProfitableToHoist(MachineInstr &MI) {
11912754fe60SDimitry Andric   if (MI.isImplicitDef())
11922754fe60SDimitry Andric     return true;
11932754fe60SDimitry Andric 
1194dff0c46cSDimitry Andric   // Besides removing computation from the loop, hoisting an instruction has
1195dff0c46cSDimitry Andric   // these effects:
1196dff0c46cSDimitry Andric   //
1197dff0c46cSDimitry Andric   // - The value defined by the instruction becomes live across the entire
1198dff0c46cSDimitry Andric   //   loop. This increases register pressure in the loop.
1199dff0c46cSDimitry Andric   //
1200dff0c46cSDimitry Andric   // - If the value is used by a PHI in the loop, a copy will be required for
1201dff0c46cSDimitry Andric   //   lowering the PHI after extending the live range.
1202dff0c46cSDimitry Andric   //
1203dff0c46cSDimitry Andric   // - When hoisting the last use of a value in the loop, that value no longer
1204dff0c46cSDimitry Andric   //   needs to be live in the loop. This lowers register pressure in the loop.
1205dff0c46cSDimitry Andric 
12064ba319b5SDimitry Andric   if (HoistConstStores &&  isCopyFeedingInvariantStore(MI, MRI, TRI))
12074ba319b5SDimitry Andric     return true;
12084ba319b5SDimitry Andric 
1209dff0c46cSDimitry Andric   bool CheapInstr = IsCheapInstruction(MI);
1210dff0c46cSDimitry Andric   bool CreatesCopy = HasLoopPHIUse(&MI);
1211dff0c46cSDimitry Andric 
1212dff0c46cSDimitry Andric   // Don't hoist a cheap instruction if it would create a copy in the loop.
1213dff0c46cSDimitry Andric   if (CheapInstr && CreatesCopy) {
12144ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
12152754fe60SDimitry Andric     return false;
1216dff0c46cSDimitry Andric   }
1217dff0c46cSDimitry Andric 
1218dff0c46cSDimitry Andric   // Rematerializable instructions should always be hoisted since the register
1219dff0c46cSDimitry Andric   // allocator can just pull them down again when needed.
12203ca95b02SDimitry Andric   if (TII->isTriviallyReMaterializable(MI, AA))
1221dff0c46cSDimitry Andric     return true;
1222dff0c46cSDimitry Andric 
12232754fe60SDimitry Andric   // FIXME: If there are long latency loop-invariant instructions inside the
12242754fe60SDimitry Andric   // loop at this point, why didn't the optimizer's LICM hoist them?
12252754fe60SDimitry Andric   for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
12262754fe60SDimitry Andric     const MachineOperand &MO = MI.getOperand(i);
12272754fe60SDimitry Andric     if (!MO.isReg() || MO.isImplicit())
12282754fe60SDimitry Andric       continue;
12292754fe60SDimitry Andric     unsigned Reg = MO.getReg();
12302754fe60SDimitry Andric     if (!TargetRegisterInfo::isVirtualRegister(Reg))
12312754fe60SDimitry Andric       continue;
1232ff0cc061SDimitry Andric     if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) {
12334ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Hoist High Latency: " << MI);
12342754fe60SDimitry Andric       ++NumHighLatency;
12352754fe60SDimitry Andric       return true;
12362754fe60SDimitry Andric     }
12372754fe60SDimitry Andric   }
1238ff0cc061SDimitry Andric 
1239ff0cc061SDimitry Andric   // Estimate register pressure to determine whether to LICM the instruction.
1240ff0cc061SDimitry Andric   // In low register pressure situation, we can be more aggressive about
1241ff0cc061SDimitry Andric   // hoisting. Also, favors hoisting long latency instructions even in
1242ff0cc061SDimitry Andric   // moderately high pressure situation.
1243ff0cc061SDimitry Andric   // Cheap instructions will only be hoisted if they don't increase register
1244ff0cc061SDimitry Andric   // pressure at all.
1245ff0cc061SDimitry Andric   auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
1246ff0cc061SDimitry Andric                                /*ConsiderUnseenAsDef=*/false);
12472754fe60SDimitry Andric 
12482754fe60SDimitry Andric   // Visit BBs from header to current BB, if hoisting this doesn't cause
12492754fe60SDimitry Andric   // high register pressure, then it's safe to proceed.
1250dff0c46cSDimitry Andric   if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
12514ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
12522754fe60SDimitry Andric     ++NumLowRP;
12532754fe60SDimitry Andric     return true;
12542754fe60SDimitry Andric   }
12552754fe60SDimitry Andric 
1256dff0c46cSDimitry Andric   // Don't risk increasing register pressure if it would create copies.
1257dff0c46cSDimitry Andric   if (CreatesCopy) {
12584ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
1259dff0c46cSDimitry Andric     return false;
1260dff0c46cSDimitry Andric   }
1261dff0c46cSDimitry Andric 
12626122f3e6SDimitry Andric   // Do not "speculate" in high register pressure situation. If an
12636122f3e6SDimitry Andric   // instruction is not guaranteed to be executed in the loop, it's best to be
12646122f3e6SDimitry Andric   // conservative.
12656122f3e6SDimitry Andric   if (AvoidSpeculation &&
1266dff0c46cSDimitry Andric       (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
12674ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Won't speculate: " << MI);
1268f22ef01cSRoman Divacky     return false;
1269f22ef01cSRoman Divacky   }
1270f22ef01cSRoman Divacky 
1271dff0c46cSDimitry Andric   // High register pressure situation, only hoist if the instruction is going
1272dff0c46cSDimitry Andric   // to be remat'ed.
1273d88c1a5aSDimitry Andric   if (!TII->isTriviallyReMaterializable(MI, AA) &&
1274d88c1a5aSDimitry Andric       !MI.isDereferenceableInvariantLoad(AA)) {
12754ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1276f22ef01cSRoman Divacky     return false;
1277f22ef01cSRoman Divacky   }
1278f22ef01cSRoman Divacky 
1279f22ef01cSRoman Divacky   return true;
1280f22ef01cSRoman Divacky }
1281f22ef01cSRoman Divacky 
12827d523365SDimitry Andric /// Unfold a load from the given machineinstr if the load itself could be
12837d523365SDimitry Andric /// hoisted. Return the unfolded and hoistable load, or null if the load
12847d523365SDimitry Andric /// couldn't be unfolded or if it wouldn't be hoistable.
ExtractHoistableLoad(MachineInstr * MI)12854ba319b5SDimitry Andric MachineInstr *MachineLICMBase::ExtractHoistableLoad(MachineInstr *MI) {
12862754fe60SDimitry Andric   // Don't unfold simple loads.
1287dff0c46cSDimitry Andric   if (MI->canFoldAsLoad())
128891bc56edSDimitry Andric     return nullptr;
12892754fe60SDimitry Andric 
1290f22ef01cSRoman Divacky   // If not, we may be able to unfold a load and hoist that.
1291f22ef01cSRoman Divacky   // First test whether the instruction is loading from an amenable
1292f22ef01cSRoman Divacky   // memory location.
1293d88c1a5aSDimitry Andric   if (!MI->isDereferenceableInvariantLoad(AA))
129491bc56edSDimitry Andric     return nullptr;
1295f22ef01cSRoman Divacky 
1296f22ef01cSRoman Divacky   // Next determine the register class for a temporary register.
1297f22ef01cSRoman Divacky   unsigned LoadRegIndex;
1298f22ef01cSRoman Divacky   unsigned NewOpc =
1299f22ef01cSRoman Divacky     TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1300f22ef01cSRoman Divacky                                     /*UnfoldLoad=*/true,
1301f22ef01cSRoman Divacky                                     /*UnfoldStore=*/false,
1302f22ef01cSRoman Divacky                                     &LoadRegIndex);
130391bc56edSDimitry Andric   if (NewOpc == 0) return nullptr;
130417a519f9SDimitry Andric   const MCInstrDesc &MID = TII->get(NewOpc);
13052cab237bSDimitry Andric   MachineFunction &MF = *MI->getMF();
13067ae0e2c9SDimitry Andric   const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
1307f22ef01cSRoman Divacky   // Ok, we're unfolding. Create a temporary register and do the unfold.
13082754fe60SDimitry Andric   unsigned Reg = MRI->createVirtualRegister(RC);
1309f22ef01cSRoman Divacky 
1310f22ef01cSRoman Divacky   SmallVector<MachineInstr *, 2> NewMIs;
13113ca95b02SDimitry Andric   bool Success = TII->unfoldMemoryOperand(MF, *MI, Reg,
13123ca95b02SDimitry Andric                                           /*UnfoldLoad=*/true,
13133ca95b02SDimitry Andric                                           /*UnfoldStore=*/false, NewMIs);
1314f22ef01cSRoman Divacky   (void)Success;
1315f22ef01cSRoman Divacky   assert(Success &&
1316f22ef01cSRoman Divacky          "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1317f22ef01cSRoman Divacky          "succeeded!");
1318f22ef01cSRoman Divacky   assert(NewMIs.size() == 2 &&
1319f22ef01cSRoman Divacky          "Unfolded a load into multiple instructions!");
1320f22ef01cSRoman Divacky   MachineBasicBlock *MBB = MI->getParent();
1321dff0c46cSDimitry Andric   MachineBasicBlock::iterator Pos = MI;
1322dff0c46cSDimitry Andric   MBB->insert(Pos, NewMIs[0]);
1323dff0c46cSDimitry Andric   MBB->insert(Pos, NewMIs[1]);
1324f22ef01cSRoman Divacky   // If unfolding produced a load that wasn't loop-invariant or profitable to
1325f22ef01cSRoman Divacky   // hoist, discard the new instructions and bail.
1326f22ef01cSRoman Divacky   if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
1327f22ef01cSRoman Divacky     NewMIs[0]->eraseFromParent();
1328f22ef01cSRoman Divacky     NewMIs[1]->eraseFromParent();
132991bc56edSDimitry Andric     return nullptr;
1330f22ef01cSRoman Divacky   }
13312754fe60SDimitry Andric 
13322754fe60SDimitry Andric   // Update register pressure for the unfolded instruction.
13332754fe60SDimitry Andric   UpdateRegPressure(NewMIs[1]);
13342754fe60SDimitry Andric 
1335f22ef01cSRoman Divacky   // Otherwise we successfully unfolded a load that we can hoist.
1336f22ef01cSRoman Divacky   MI->eraseFromParent();
1337f22ef01cSRoman Divacky   return NewMIs[0];
1338f22ef01cSRoman Divacky }
1339f22ef01cSRoman Divacky 
13407d523365SDimitry Andric /// Initialize the CSE map with instructions that are in the current loop
13417d523365SDimitry Andric /// preheader that may become duplicates of instructions that are hoisted
13427d523365SDimitry Andric /// out of the loop.
InitCSEMap(MachineBasicBlock * BB)13434ba319b5SDimitry Andric void MachineLICMBase::InitCSEMap(MachineBasicBlock *BB) {
1344444ed5c5SDimitry Andric   for (MachineInstr &MI : *BB)
1345444ed5c5SDimitry Andric     CSEMap[MI.getOpcode()].push_back(&MI);
1346f22ef01cSRoman Divacky }
1347f22ef01cSRoman Divacky 
13487d523365SDimitry Andric /// Find an instruction amount PrevMIs that is a duplicate of MI.
13497d523365SDimitry Andric /// Return this instruction if it's found.
1350f22ef01cSRoman Divacky const MachineInstr*
LookForDuplicate(const MachineInstr * MI,std::vector<const MachineInstr * > & PrevMIs)13514ba319b5SDimitry Andric MachineLICMBase::LookForDuplicate(const MachineInstr *MI,
1352f22ef01cSRoman Divacky                                   std::vector<const MachineInstr*> &PrevMIs) {
1353444ed5c5SDimitry Andric   for (const MachineInstr *PrevMI : PrevMIs)
13543ca95b02SDimitry Andric     if (TII->produceSameValue(*MI, *PrevMI, (PreRegAlloc ? MRI : nullptr)))
1355f22ef01cSRoman Divacky       return PrevMI;
1356444ed5c5SDimitry Andric 
135791bc56edSDimitry Andric   return nullptr;
1358f22ef01cSRoman Divacky }
1359f22ef01cSRoman Divacky 
13607d523365SDimitry Andric /// Given a LICM'ed instruction, look for an instruction on the preheader that
13617d523365SDimitry Andric /// computes the same value. If it's found, do a RAU on with the definition of
13627d523365SDimitry Andric /// the existing instruction rather than hoisting the instruction to the
13637d523365SDimitry Andric /// preheader.
EliminateCSE(MachineInstr * MI,DenseMap<unsigned,std::vector<const MachineInstr * >>::iterator & CI)13644ba319b5SDimitry Andric bool MachineLICMBase::EliminateCSE(MachineInstr *MI,
1365f22ef01cSRoman Divacky     DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI) {
1366ffd1746dSEd Schouten   // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1367ffd1746dSEd Schouten   // the undef property onto uses.
1368ffd1746dSEd Schouten   if (CI == CSEMap.end() || MI->isImplicitDef())
1369f22ef01cSRoman Divacky     return false;
1370f22ef01cSRoman Divacky 
1371f22ef01cSRoman Divacky   if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
13724ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
1373f22ef01cSRoman Divacky 
1374f22ef01cSRoman Divacky     // Replace virtual registers defined by MI by their counterparts defined
1375f22ef01cSRoman Divacky     // by Dup.
1376dff0c46cSDimitry Andric     SmallVector<unsigned, 2> Defs;
1377f22ef01cSRoman Divacky     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1378f22ef01cSRoman Divacky       const MachineOperand &MO = MI->getOperand(i);
1379f22ef01cSRoman Divacky 
1380f22ef01cSRoman Divacky       // Physical registers may not differ here.
1381f22ef01cSRoman Divacky       assert((!MO.isReg() || MO.getReg() == 0 ||
1382f22ef01cSRoman Divacky               !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1383f22ef01cSRoman Divacky               MO.getReg() == Dup->getOperand(i).getReg()) &&
1384f22ef01cSRoman Divacky              "Instructions with different phys regs are not identical!");
1385f22ef01cSRoman Divacky 
1386f22ef01cSRoman Divacky       if (MO.isReg() && MO.isDef() &&
1387dff0c46cSDimitry Andric           !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1388dff0c46cSDimitry Andric         Defs.push_back(i);
1389dff0c46cSDimitry Andric     }
1390dff0c46cSDimitry Andric 
1391dff0c46cSDimitry Andric     SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1392dff0c46cSDimitry Andric     for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1393dff0c46cSDimitry Andric       unsigned Idx = Defs[i];
1394dff0c46cSDimitry Andric       unsigned Reg = MI->getOperand(Idx).getReg();
1395dff0c46cSDimitry Andric       unsigned DupReg = Dup->getOperand(Idx).getReg();
1396dff0c46cSDimitry Andric       OrigRCs.push_back(MRI->getRegClass(DupReg));
1397dff0c46cSDimitry Andric 
1398dff0c46cSDimitry Andric       if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1399dff0c46cSDimitry Andric         // Restore old RCs if more than one defs.
1400dff0c46cSDimitry Andric         for (unsigned j = 0; j != i; ++j)
1401dff0c46cSDimitry Andric           MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1402dff0c46cSDimitry Andric         return false;
1403f22ef01cSRoman Divacky       }
1404f22ef01cSRoman Divacky     }
1405dff0c46cSDimitry Andric 
1406444ed5c5SDimitry Andric     for (unsigned Idx : Defs) {
1407dff0c46cSDimitry Andric       unsigned Reg = MI->getOperand(Idx).getReg();
1408dff0c46cSDimitry Andric       unsigned DupReg = Dup->getOperand(Idx).getReg();
1409dff0c46cSDimitry Andric       MRI->replaceRegWith(Reg, DupReg);
1410dff0c46cSDimitry Andric       MRI->clearKillFlags(DupReg);
1411dff0c46cSDimitry Andric     }
1412dff0c46cSDimitry Andric 
1413f22ef01cSRoman Divacky     MI->eraseFromParent();
1414f22ef01cSRoman Divacky     ++NumCSEed;
1415f22ef01cSRoman Divacky     return true;
1416f22ef01cSRoman Divacky   }
1417f22ef01cSRoman Divacky   return false;
1418f22ef01cSRoman Divacky }
1419f22ef01cSRoman Divacky 
14207d523365SDimitry Andric /// Return true if the given instruction will be CSE'd if it's hoisted out of
14217d523365SDimitry Andric /// the loop.
MayCSE(MachineInstr * MI)14224ba319b5SDimitry Andric bool MachineLICMBase::MayCSE(MachineInstr *MI) {
14236122f3e6SDimitry Andric   unsigned Opcode = MI->getOpcode();
14246122f3e6SDimitry Andric   DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator
14256122f3e6SDimitry Andric     CI = CSEMap.find(Opcode);
14266122f3e6SDimitry Andric   // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
14276122f3e6SDimitry Andric   // the undef property onto uses.
14286122f3e6SDimitry Andric   if (CI == CSEMap.end() || MI->isImplicitDef())
14296122f3e6SDimitry Andric     return false;
14306122f3e6SDimitry Andric 
143191bc56edSDimitry Andric   return LookForDuplicate(MI, CI->second) != nullptr;
14326122f3e6SDimitry Andric }
14336122f3e6SDimitry Andric 
14347d523365SDimitry Andric /// When an instruction is found to use only loop invariant operands
1435f22ef01cSRoman Divacky /// that are safe to hoist, this instruction is called to do the dirty work.
14367d523365SDimitry Andric /// It returns true if the instruction is hoisted.
Hoist(MachineInstr * MI,MachineBasicBlock * Preheader)14374ba319b5SDimitry Andric bool MachineLICMBase::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
1438f22ef01cSRoman Divacky   // First check whether we should hoist this instruction.
1439f22ef01cSRoman Divacky   if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
1440f22ef01cSRoman Divacky     // If not, try unfolding a hoistable load.
1441f22ef01cSRoman Divacky     MI = ExtractHoistableLoad(MI);
14422754fe60SDimitry Andric     if (!MI) return false;
1443f22ef01cSRoman Divacky   }
1444f22ef01cSRoman Divacky 
14454ba319b5SDimitry Andric   // If we have hoisted an instruction that may store, it can only be a constant
14464ba319b5SDimitry Andric   // store.
14474ba319b5SDimitry Andric   if (MI->mayStore())
14484ba319b5SDimitry Andric     NumStoreConst++;
14494ba319b5SDimitry Andric 
1450f22ef01cSRoman Divacky   // Now move the instructions to the predecessor, inserting it before any
1451f22ef01cSRoman Divacky   // terminator instructions.
14524ba319b5SDimitry Andric   LLVM_DEBUG({
1453f22ef01cSRoman Divacky     dbgs() << "Hoisting " << *MI;
1454f22ef01cSRoman Divacky     if (MI->getParent()->getBasicBlock())
14552cab237bSDimitry Andric       dbgs() << " from " << printMBBReference(*MI->getParent());
14563ca95b02SDimitry Andric     if (Preheader->getBasicBlock())
14572cab237bSDimitry Andric       dbgs() << " to " << printMBBReference(*Preheader);
1458f22ef01cSRoman Divacky     dbgs() << "\n";
1459f22ef01cSRoman Divacky   });
1460f22ef01cSRoman Divacky 
1461f22ef01cSRoman Divacky   // If this is the first instruction being hoisted to the preheader,
1462f22ef01cSRoman Divacky   // initialize the CSE map with potential common expressions.
1463ffd1746dSEd Schouten   if (FirstInLoop) {
1464ffd1746dSEd Schouten     InitCSEMap(Preheader);
1465ffd1746dSEd Schouten     FirstInLoop = false;
1466ffd1746dSEd Schouten   }
1467f22ef01cSRoman Divacky 
1468f22ef01cSRoman Divacky   // Look for opportunity to CSE the hoisted instruction.
1469f22ef01cSRoman Divacky   unsigned Opcode = MI->getOpcode();
1470f22ef01cSRoman Divacky   DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator
1471f22ef01cSRoman Divacky     CI = CSEMap.find(Opcode);
1472f22ef01cSRoman Divacky   if (!EliminateCSE(MI, CI)) {
1473f22ef01cSRoman Divacky     // Otherwise, splice the instruction to the preheader.
1474ffd1746dSEd Schouten     Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
1475f22ef01cSRoman Divacky 
1476d88c1a5aSDimitry Andric     // Since we are moving the instruction out of its basic block, we do not
1477d88c1a5aSDimitry Andric     // retain its debug location. Doing so would degrade the debugging
1478d88c1a5aSDimitry Andric     // experience and adversely affect the accuracy of profiling information.
1479d88c1a5aSDimitry Andric     MI->setDebugLoc(DebugLoc());
1480d88c1a5aSDimitry Andric 
14812754fe60SDimitry Andric     // Update register pressure for BBs from header to this block.
14822754fe60SDimitry Andric     UpdateBackTraceRegPressure(MI);
14832754fe60SDimitry Andric 
1484f22ef01cSRoman Divacky     // Clear the kill flags of any register this instruction defines,
1485f22ef01cSRoman Divacky     // since they may need to be live throughout the entire loop
1486f22ef01cSRoman Divacky     // rather than just live for part of it.
1487444ed5c5SDimitry Andric     for (MachineOperand &MO : MI->operands())
1488f22ef01cSRoman Divacky       if (MO.isReg() && MO.isDef() && !MO.isDead())
14892754fe60SDimitry Andric         MRI->clearKillFlags(MO.getReg());
1490f22ef01cSRoman Divacky 
1491f22ef01cSRoman Divacky     // Add to the CSE map.
1492f22ef01cSRoman Divacky     if (CI != CSEMap.end())
1493f22ef01cSRoman Divacky       CI->second.push_back(MI);
149439d628a0SDimitry Andric     else
149539d628a0SDimitry Andric       CSEMap[Opcode].push_back(MI);
1496f22ef01cSRoman Divacky   }
1497f22ef01cSRoman Divacky 
1498f22ef01cSRoman Divacky   ++NumHoisted;
1499f22ef01cSRoman Divacky   Changed = true;
15002754fe60SDimitry Andric 
15012754fe60SDimitry Andric   return true;
1502f22ef01cSRoman Divacky }
1503ffd1746dSEd Schouten 
15047d523365SDimitry Andric /// Get the preheader for the current loop, splitting a critical edge if needed.
getCurPreheader()15054ba319b5SDimitry Andric MachineBasicBlock *MachineLICMBase::getCurPreheader() {
1506ffd1746dSEd Schouten   // Determine the block to which to hoist instructions. If we can't find a
1507ffd1746dSEd Schouten   // suitable loop predecessor, we can't do any hoisting.
1508ffd1746dSEd Schouten 
1509ffd1746dSEd Schouten   // If we've tried to get a preheader and failed, don't try again.
1510ffd1746dSEd Schouten   if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
151191bc56edSDimitry Andric     return nullptr;
1512ffd1746dSEd Schouten 
1513ffd1746dSEd Schouten   if (!CurPreheader) {
1514ffd1746dSEd Schouten     CurPreheader = CurLoop->getLoopPreheader();
1515ffd1746dSEd Schouten     if (!CurPreheader) {
1516ffd1746dSEd Schouten       MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1517ffd1746dSEd Schouten       if (!Pred) {
1518ffd1746dSEd Schouten         CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
151991bc56edSDimitry Andric         return nullptr;
1520ffd1746dSEd Schouten       }
1521ffd1746dSEd Schouten 
15223ca95b02SDimitry Andric       CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), *this);
1523ffd1746dSEd Schouten       if (!CurPreheader) {
1524ffd1746dSEd Schouten         CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
152591bc56edSDimitry Andric         return nullptr;
1526ffd1746dSEd Schouten       }
1527ffd1746dSEd Schouten     }
1528ffd1746dSEd Schouten   }
1529ffd1746dSEd Schouten   return CurPreheader;
1530ffd1746dSEd Schouten }
1531