10b57cec5SDimitry Andric //===- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ----------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This pass performs loop invariant code motion on machine instructions. We
100b57cec5SDimitry Andric // attempt to remove as much code from the body of a loop as possible.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric // This pass is not intended to be a replacement or a complete alternative
130b57cec5SDimitry Andric // for the LLVM-IR-level LICM pass. It is only designed to hoist simple
140b57cec5SDimitry Andric // constructs that are not exposed before lowering and instruction selection.
150b57cec5SDimitry Andric //
160b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
170b57cec5SDimitry Andric 
180b57cec5SDimitry Andric #include "llvm/ADT/BitVector.h"
190b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
200b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
210b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
220b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
230b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
240b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
26480093f4SDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
300b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
310b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
320b57cec5SDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h"
330b57cec5SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
350b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
360b57cec5SDimitry Andric #include "llvm/CodeGen/PseudoSourceValue.h"
370b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
380b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
390b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
400b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSchedule.h"
410b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
420b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
43480093f4SDimitry Andric #include "llvm/InitializePasses.h"
440b57cec5SDimitry Andric #include "llvm/MC/MCInstrDesc.h"
45af732203SDimitry Andric #include "llvm/MC/MCRegister.h"
460b57cec5SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
470b57cec5SDimitry Andric #include "llvm/Pass.h"
480b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
490b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
500b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
510b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
520b57cec5SDimitry Andric #include <algorithm>
530b57cec5SDimitry Andric #include <cassert>
540b57cec5SDimitry Andric #include <limits>
550b57cec5SDimitry Andric #include <vector>
560b57cec5SDimitry Andric 
570b57cec5SDimitry Andric using namespace llvm;
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric #define DEBUG_TYPE "machinelicm"
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric static cl::opt<bool>
620b57cec5SDimitry Andric AvoidSpeculation("avoid-speculation",
630b57cec5SDimitry Andric                  cl::desc("MachineLICM should avoid speculation"),
640b57cec5SDimitry Andric                  cl::init(true), cl::Hidden);
650b57cec5SDimitry Andric 
660b57cec5SDimitry Andric static cl::opt<bool>
670b57cec5SDimitry Andric HoistCheapInsts("hoist-cheap-insts",
680b57cec5SDimitry Andric                 cl::desc("MachineLICM should hoist even cheap instructions"),
690b57cec5SDimitry Andric                 cl::init(false), cl::Hidden);
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric static cl::opt<bool>
720b57cec5SDimitry Andric HoistConstStores("hoist-const-stores",
730b57cec5SDimitry Andric                  cl::desc("Hoist invariant stores"),
740b57cec5SDimitry Andric                  cl::init(true), cl::Hidden);
75480093f4SDimitry Andric // The default threshold of 100 (i.e. if target block is 100 times hotter)
76480093f4SDimitry Andric // is based on empirical data on a single target and is subject to tuning.
77480093f4SDimitry Andric static cl::opt<unsigned>
78480093f4SDimitry Andric BlockFrequencyRatioThreshold("block-freq-ratio-threshold",
79480093f4SDimitry Andric                              cl::desc("Do not hoist instructions if target"
80480093f4SDimitry Andric                              "block is N times hotter than the source."),
81480093f4SDimitry Andric                              cl::init(100), cl::Hidden);
82480093f4SDimitry Andric 
83480093f4SDimitry Andric enum class UseBFI { None, PGO, All };
84480093f4SDimitry Andric 
85480093f4SDimitry Andric static cl::opt<UseBFI>
86480093f4SDimitry Andric DisableHoistingToHotterBlocks("disable-hoisting-to-hotter-blocks",
87480093f4SDimitry Andric                               cl::desc("Disable hoisting instructions to"
88480093f4SDimitry Andric                               " hotter blocks"),
89af732203SDimitry Andric                               cl::init(UseBFI::PGO), cl::Hidden,
90480093f4SDimitry Andric                               cl::values(clEnumValN(UseBFI::None, "none",
91480093f4SDimitry Andric                               "disable the feature"),
92480093f4SDimitry Andric                               clEnumValN(UseBFI::PGO, "pgo",
93480093f4SDimitry Andric                               "enable the feature when using profile data"),
94480093f4SDimitry Andric                               clEnumValN(UseBFI::All, "all",
95480093f4SDimitry Andric                               "enable the feature with/wo profile data")));
960b57cec5SDimitry Andric 
970b57cec5SDimitry Andric STATISTIC(NumHoisted,
980b57cec5SDimitry Andric           "Number of machine instructions hoisted out of loops");
990b57cec5SDimitry Andric STATISTIC(NumLowRP,
1000b57cec5SDimitry Andric           "Number of instructions hoisted in low reg pressure situation");
1010b57cec5SDimitry Andric STATISTIC(NumHighLatency,
1020b57cec5SDimitry Andric           "Number of high latency instructions hoisted");
1030b57cec5SDimitry Andric STATISTIC(NumCSEed,
1040b57cec5SDimitry Andric           "Number of hoisted machine instructions CSEed");
1050b57cec5SDimitry Andric STATISTIC(NumPostRAHoisted,
1060b57cec5SDimitry Andric           "Number of machine instructions hoisted out of loops post regalloc");
1070b57cec5SDimitry Andric STATISTIC(NumStoreConst,
1080b57cec5SDimitry Andric           "Number of stores of const phys reg hoisted out of loops");
109480093f4SDimitry Andric STATISTIC(NumNotHoistedDueToHotness,
110480093f4SDimitry Andric           "Number of instructions not hoisted due to block frequency");
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric namespace {
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric   class MachineLICMBase : public MachineFunctionPass {
1150b57cec5SDimitry Andric     const TargetInstrInfo *TII;
1160b57cec5SDimitry Andric     const TargetLoweringBase *TLI;
1170b57cec5SDimitry Andric     const TargetRegisterInfo *TRI;
1180b57cec5SDimitry Andric     const MachineFrameInfo *MFI;
1190b57cec5SDimitry Andric     MachineRegisterInfo *MRI;
1200b57cec5SDimitry Andric     TargetSchedModel SchedModel;
1210b57cec5SDimitry Andric     bool PreRegAlloc;
122480093f4SDimitry Andric     bool HasProfileData;
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric     // Various analyses that we use...
1250b57cec5SDimitry Andric     AliasAnalysis        *AA;      // Alias analysis info.
126480093f4SDimitry Andric     MachineBlockFrequencyInfo *MBFI; // Machine block frequncy info
1270b57cec5SDimitry Andric     MachineLoopInfo      *MLI;     // Current MachineLoopInfo
1280b57cec5SDimitry Andric     MachineDominatorTree *DT;      // Machine dominator tree for the cur loop
1290b57cec5SDimitry Andric 
1300b57cec5SDimitry Andric     // State that is updated as we process loops
1310b57cec5SDimitry Andric     bool         Changed;          // True if a loop is changed.
1320b57cec5SDimitry Andric     bool         FirstInLoop;      // True if it's the first LICM in the loop.
1330b57cec5SDimitry Andric     MachineLoop *CurLoop;          // The current loop we are working on.
1340b57cec5SDimitry Andric     MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric     // Exit blocks for CurLoop.
1370b57cec5SDimitry Andric     SmallVector<MachineBasicBlock *, 8> ExitBlocks;
1380b57cec5SDimitry Andric 
isExitBlock(const MachineBasicBlock * MBB) const1390b57cec5SDimitry Andric     bool isExitBlock(const MachineBasicBlock *MBB) const {
1400b57cec5SDimitry Andric       return is_contained(ExitBlocks, MBB);
1410b57cec5SDimitry Andric     }
1420b57cec5SDimitry Andric 
1430b57cec5SDimitry Andric     // Track 'estimated' register pressure.
144af732203SDimitry Andric     SmallSet<Register, 32> RegSeen;
1450b57cec5SDimitry Andric     SmallVector<unsigned, 8> RegPressure;
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric     // Register pressure "limit" per register pressure set. If the pressure
1480b57cec5SDimitry Andric     // is higher than the limit, then it's considered high.
1490b57cec5SDimitry Andric     SmallVector<unsigned, 8> RegLimit;
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric     // Register pressure on path leading from loop preheader to current BB.
1520b57cec5SDimitry Andric     SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric     // For each opcode, keep a list of potential CSE instructions.
155af732203SDimitry Andric     DenseMap<unsigned, std::vector<MachineInstr *>> CSEMap;
1560b57cec5SDimitry Andric 
1570b57cec5SDimitry Andric     enum {
1580b57cec5SDimitry Andric       SpeculateFalse   = 0,
1590b57cec5SDimitry Andric       SpeculateTrue    = 1,
1600b57cec5SDimitry Andric       SpeculateUnknown = 2
1610b57cec5SDimitry Andric     };
1620b57cec5SDimitry Andric 
1630b57cec5SDimitry Andric     // If a MBB does not dominate loop exiting blocks then it may not safe
1640b57cec5SDimitry Andric     // to hoist loads from this block.
1650b57cec5SDimitry Andric     // Tri-state: 0 - false, 1 - true, 2 - unknown
1660b57cec5SDimitry Andric     unsigned SpeculationState;
1670b57cec5SDimitry Andric 
1680b57cec5SDimitry Andric   public:
MachineLICMBase(char & PassID,bool PreRegAlloc)1690b57cec5SDimitry Andric     MachineLICMBase(char &PassID, bool PreRegAlloc)
1700b57cec5SDimitry Andric         : MachineFunctionPass(PassID), PreRegAlloc(PreRegAlloc) {}
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric     bool runOnMachineFunction(MachineFunction &MF) override;
1730b57cec5SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const1740b57cec5SDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
1750b57cec5SDimitry Andric       AU.addRequired<MachineLoopInfo>();
176480093f4SDimitry Andric       if (DisableHoistingToHotterBlocks != UseBFI::None)
177480093f4SDimitry Andric         AU.addRequired<MachineBlockFrequencyInfo>();
1780b57cec5SDimitry Andric       AU.addRequired<MachineDominatorTree>();
1790b57cec5SDimitry Andric       AU.addRequired<AAResultsWrapperPass>();
1800b57cec5SDimitry Andric       AU.addPreserved<MachineLoopInfo>();
1810b57cec5SDimitry Andric       MachineFunctionPass::getAnalysisUsage(AU);
1820b57cec5SDimitry Andric     }
1830b57cec5SDimitry Andric 
releaseMemory()1840b57cec5SDimitry Andric     void releaseMemory() override {
1850b57cec5SDimitry Andric       RegSeen.clear();
1860b57cec5SDimitry Andric       RegPressure.clear();
1870b57cec5SDimitry Andric       RegLimit.clear();
1880b57cec5SDimitry Andric       BackTrace.clear();
1890b57cec5SDimitry Andric       CSEMap.clear();
1900b57cec5SDimitry Andric     }
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric   private:
1930b57cec5SDimitry Andric     /// Keep track of information about hoisting candidates.
1940b57cec5SDimitry Andric     struct CandidateInfo {
1950b57cec5SDimitry Andric       MachineInstr *MI;
1960b57cec5SDimitry Andric       unsigned      Def;
1970b57cec5SDimitry Andric       int           FI;
1980b57cec5SDimitry Andric 
CandidateInfo__anon3ed712e20111::MachineLICMBase::CandidateInfo1990b57cec5SDimitry Andric       CandidateInfo(MachineInstr *mi, unsigned def, int fi)
2000b57cec5SDimitry Andric         : MI(mi), Def(def), FI(fi) {}
2010b57cec5SDimitry Andric     };
2020b57cec5SDimitry Andric 
2030b57cec5SDimitry Andric     void HoistRegionPostRA();
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric     void HoistPostRA(MachineInstr *MI, unsigned Def);
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric     void ProcessMI(MachineInstr *MI, BitVector &PhysRegDefs,
2080b57cec5SDimitry Andric                    BitVector &PhysRegClobbers, SmallSet<int, 32> &StoredFIs,
2090b57cec5SDimitry Andric                    SmallVectorImpl<CandidateInfo> &Candidates);
2100b57cec5SDimitry Andric 
211af732203SDimitry Andric     void AddToLiveIns(MCRegister Reg);
2120b57cec5SDimitry Andric 
2130b57cec5SDimitry Andric     bool IsLICMCandidate(MachineInstr &I);
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric     bool IsLoopInvariantInst(MachineInstr &I);
2160b57cec5SDimitry Andric 
2170b57cec5SDimitry Andric     bool HasLoopPHIUse(const MachineInstr *MI) const;
2180b57cec5SDimitry Andric 
2190b57cec5SDimitry Andric     bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
220af732203SDimitry Andric                                Register Reg) const;
2210b57cec5SDimitry Andric 
2220b57cec5SDimitry Andric     bool IsCheapInstruction(MachineInstr &MI) const;
2230b57cec5SDimitry Andric 
2240b57cec5SDimitry Andric     bool CanCauseHighRegPressure(const DenseMap<unsigned, int> &Cost,
2250b57cec5SDimitry Andric                                  bool Cheap);
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric     void UpdateBackTraceRegPressure(const MachineInstr *MI);
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric     bool IsProfitableToHoist(MachineInstr &MI);
2300b57cec5SDimitry Andric 
2310b57cec5SDimitry Andric     bool IsGuaranteedToExecute(MachineBasicBlock *BB);
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric     void EnterScope(MachineBasicBlock *MBB);
2340b57cec5SDimitry Andric 
2350b57cec5SDimitry Andric     void ExitScope(MachineBasicBlock *MBB);
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric     void ExitScopeIfDone(
2380b57cec5SDimitry Andric         MachineDomTreeNode *Node,
2390b57cec5SDimitry Andric         DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren,
2400b57cec5SDimitry Andric         DenseMap<MachineDomTreeNode *, MachineDomTreeNode *> &ParentMap);
2410b57cec5SDimitry Andric 
2420b57cec5SDimitry Andric     void HoistOutOfLoop(MachineDomTreeNode *HeaderN);
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric     void InitRegPressure(MachineBasicBlock *BB);
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric     DenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI,
2470b57cec5SDimitry Andric                                              bool ConsiderSeen,
2480b57cec5SDimitry Andric                                              bool ConsiderUnseenAsDef);
2490b57cec5SDimitry Andric 
2500b57cec5SDimitry Andric     void UpdateRegPressure(const MachineInstr *MI,
2510b57cec5SDimitry Andric                            bool ConsiderUnseenAsDef = false);
2520b57cec5SDimitry Andric 
2530b57cec5SDimitry Andric     MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
2540b57cec5SDimitry Andric 
255af732203SDimitry Andric     MachineInstr *LookForDuplicate(const MachineInstr *MI,
256af732203SDimitry Andric                                    std::vector<MachineInstr *> &PrevMIs);
2570b57cec5SDimitry Andric 
258af732203SDimitry Andric     bool
259af732203SDimitry Andric     EliminateCSE(MachineInstr *MI,
260af732203SDimitry Andric                  DenseMap<unsigned, std::vector<MachineInstr *>>::iterator &CI);
2610b57cec5SDimitry Andric 
2620b57cec5SDimitry Andric     bool MayCSE(MachineInstr *MI);
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric     bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric     void InitCSEMap(MachineBasicBlock *BB);
2670b57cec5SDimitry Andric 
268480093f4SDimitry Andric     bool isTgtHotterThanSrc(MachineBasicBlock *SrcBlock,
269480093f4SDimitry Andric                             MachineBasicBlock *TgtBlock);
2700b57cec5SDimitry Andric     MachineBasicBlock *getCurPreheader();
2710b57cec5SDimitry Andric   };
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric   class MachineLICM : public MachineLICMBase {
2740b57cec5SDimitry Andric   public:
2750b57cec5SDimitry Andric     static char ID;
MachineLICM()2760b57cec5SDimitry Andric     MachineLICM() : MachineLICMBase(ID, false) {
2770b57cec5SDimitry Andric       initializeMachineLICMPass(*PassRegistry::getPassRegistry());
2780b57cec5SDimitry Andric     }
2790b57cec5SDimitry Andric   };
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric   class EarlyMachineLICM : public MachineLICMBase {
2820b57cec5SDimitry Andric   public:
2830b57cec5SDimitry Andric     static char ID;
EarlyMachineLICM()2840b57cec5SDimitry Andric     EarlyMachineLICM() : MachineLICMBase(ID, true) {
2850b57cec5SDimitry Andric       initializeEarlyMachineLICMPass(*PassRegistry::getPassRegistry());
2860b57cec5SDimitry Andric     }
2870b57cec5SDimitry Andric   };
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric } // end anonymous namespace
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric char MachineLICM::ID;
2920b57cec5SDimitry Andric char EarlyMachineLICM::ID;
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric char &llvm::MachineLICMID = MachineLICM::ID;
2950b57cec5SDimitry Andric char &llvm::EarlyMachineLICMID = EarlyMachineLICM::ID;
2960b57cec5SDimitry Andric 
2970b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(MachineLICM, DEBUG_TYPE,
2980b57cec5SDimitry Andric                       "Machine Loop Invariant Code Motion", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)2990b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
300480093f4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
3010b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
3020b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3030b57cec5SDimitry Andric INITIALIZE_PASS_END(MachineLICM, DEBUG_TYPE,
3040b57cec5SDimitry Andric                     "Machine Loop Invariant Code Motion", false, false)
3050b57cec5SDimitry Andric 
3060b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(EarlyMachineLICM, "early-machinelicm",
3070b57cec5SDimitry Andric                       "Early Machine Loop Invariant Code Motion", false, false)
3080b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
309480093f4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
3100b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
3110b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3120b57cec5SDimitry Andric INITIALIZE_PASS_END(EarlyMachineLICM, "early-machinelicm",
3130b57cec5SDimitry Andric                     "Early Machine Loop Invariant Code Motion", false, false)
3140b57cec5SDimitry Andric 
3150b57cec5SDimitry Andric /// Test if the given loop is the outer-most loop that has a unique predecessor.
3160b57cec5SDimitry Andric static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
3170b57cec5SDimitry Andric   // Check whether this loop even has a unique predecessor.
3180b57cec5SDimitry Andric   if (!CurLoop->getLoopPredecessor())
3190b57cec5SDimitry Andric     return false;
3200b57cec5SDimitry Andric   // Ok, now check to see if any of its outer loops do.
3210b57cec5SDimitry Andric   for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
3220b57cec5SDimitry Andric     if (L->getLoopPredecessor())
3230b57cec5SDimitry Andric       return false;
3240b57cec5SDimitry Andric   // None of them did, so this is the outermost with a unique predecessor.
3250b57cec5SDimitry Andric   return true;
3260b57cec5SDimitry Andric }
3270b57cec5SDimitry Andric 
runOnMachineFunction(MachineFunction & MF)3280b57cec5SDimitry Andric bool MachineLICMBase::runOnMachineFunction(MachineFunction &MF) {
3290b57cec5SDimitry Andric   if (skipFunction(MF.getFunction()))
3300b57cec5SDimitry Andric     return false;
3310b57cec5SDimitry Andric 
3320b57cec5SDimitry Andric   Changed = FirstInLoop = false;
3330b57cec5SDimitry Andric   const TargetSubtargetInfo &ST = MF.getSubtarget();
3340b57cec5SDimitry Andric   TII = ST.getInstrInfo();
3350b57cec5SDimitry Andric   TLI = ST.getTargetLowering();
3360b57cec5SDimitry Andric   TRI = ST.getRegisterInfo();
3370b57cec5SDimitry Andric   MFI = &MF.getFrameInfo();
3380b57cec5SDimitry Andric   MRI = &MF.getRegInfo();
3390b57cec5SDimitry Andric   SchedModel.init(&ST);
3400b57cec5SDimitry Andric 
3410b57cec5SDimitry Andric   PreRegAlloc = MRI->isSSA();
342480093f4SDimitry Andric   HasProfileData = MF.getFunction().hasProfileData();
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric   if (PreRegAlloc)
3450b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
3460b57cec5SDimitry Andric   else
3470b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
3480b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << MF.getName() << " ********\n");
3490b57cec5SDimitry Andric 
3500b57cec5SDimitry Andric   if (PreRegAlloc) {
3510b57cec5SDimitry Andric     // Estimate register pressure during pre-regalloc pass.
3520b57cec5SDimitry Andric     unsigned NumRPS = TRI->getNumRegPressureSets();
3530b57cec5SDimitry Andric     RegPressure.resize(NumRPS);
3540b57cec5SDimitry Andric     std::fill(RegPressure.begin(), RegPressure.end(), 0);
3550b57cec5SDimitry Andric     RegLimit.resize(NumRPS);
3560b57cec5SDimitry Andric     for (unsigned i = 0, e = NumRPS; i != e; ++i)
3570b57cec5SDimitry Andric       RegLimit[i] = TRI->getRegPressureSetLimit(MF, i);
3580b57cec5SDimitry Andric   }
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric   // Get our Loop information...
361480093f4SDimitry Andric   if (DisableHoistingToHotterBlocks != UseBFI::None)
362480093f4SDimitry Andric     MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
3630b57cec5SDimitry Andric   MLI = &getAnalysis<MachineLoopInfo>();
3640b57cec5SDimitry Andric   DT  = &getAnalysis<MachineDominatorTree>();
3650b57cec5SDimitry Andric   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3660b57cec5SDimitry Andric 
3670b57cec5SDimitry Andric   SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
3680b57cec5SDimitry Andric   while (!Worklist.empty()) {
3690b57cec5SDimitry Andric     CurLoop = Worklist.pop_back_val();
3700b57cec5SDimitry Andric     CurPreheader = nullptr;
3710b57cec5SDimitry Andric     ExitBlocks.clear();
3720b57cec5SDimitry Andric 
3730b57cec5SDimitry Andric     // If this is done before regalloc, only visit outer-most preheader-sporting
3740b57cec5SDimitry Andric     // loops.
3750b57cec5SDimitry Andric     if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
3760b57cec5SDimitry Andric       Worklist.append(CurLoop->begin(), CurLoop->end());
3770b57cec5SDimitry Andric       continue;
3780b57cec5SDimitry Andric     }
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric     CurLoop->getExitBlocks(ExitBlocks);
3810b57cec5SDimitry Andric 
3820b57cec5SDimitry Andric     if (!PreRegAlloc)
3830b57cec5SDimitry Andric       HoistRegionPostRA();
3840b57cec5SDimitry Andric     else {
3850b57cec5SDimitry Andric       // CSEMap is initialized for loop header when the first instruction is
3860b57cec5SDimitry Andric       // being hoisted.
3870b57cec5SDimitry Andric       MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
3880b57cec5SDimitry Andric       FirstInLoop = true;
3890b57cec5SDimitry Andric       HoistOutOfLoop(N);
3900b57cec5SDimitry Andric       CSEMap.clear();
3910b57cec5SDimitry Andric     }
3920b57cec5SDimitry Andric   }
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric   return Changed;
3950b57cec5SDimitry Andric }
3960b57cec5SDimitry Andric 
3970b57cec5SDimitry Andric /// Return true if instruction stores to the specified frame.
InstructionStoresToFI(const MachineInstr * MI,int FI)3980b57cec5SDimitry Andric static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
3990b57cec5SDimitry Andric   // Check mayStore before memory operands so that e.g. DBG_VALUEs will return
4000b57cec5SDimitry Andric   // true since they have no memory operands.
4010b57cec5SDimitry Andric   if (!MI->mayStore())
4020b57cec5SDimitry Andric      return false;
4030b57cec5SDimitry Andric   // If we lost memory operands, conservatively assume that the instruction
4040b57cec5SDimitry Andric   // writes to all slots.
4050b57cec5SDimitry Andric   if (MI->memoperands_empty())
4060b57cec5SDimitry Andric     return true;
4070b57cec5SDimitry Andric   for (const MachineMemOperand *MemOp : MI->memoperands()) {
4080b57cec5SDimitry Andric     if (!MemOp->isStore() || !MemOp->getPseudoValue())
4090b57cec5SDimitry Andric       continue;
4100b57cec5SDimitry Andric     if (const FixedStackPseudoSourceValue *Value =
4110b57cec5SDimitry Andric         dyn_cast<FixedStackPseudoSourceValue>(MemOp->getPseudoValue())) {
4120b57cec5SDimitry Andric       if (Value->getFrameIndex() == FI)
4130b57cec5SDimitry Andric         return true;
4140b57cec5SDimitry Andric     }
4150b57cec5SDimitry Andric   }
4160b57cec5SDimitry Andric   return false;
4170b57cec5SDimitry Andric }
4180b57cec5SDimitry Andric 
4190b57cec5SDimitry Andric /// Examine the instruction for potentai LICM candidate. Also
4200b57cec5SDimitry Andric /// gather register def and frame object update information.
ProcessMI(MachineInstr * MI,BitVector & PhysRegDefs,BitVector & PhysRegClobbers,SmallSet<int,32> & StoredFIs,SmallVectorImpl<CandidateInfo> & Candidates)4210b57cec5SDimitry Andric void MachineLICMBase::ProcessMI(MachineInstr *MI,
4220b57cec5SDimitry Andric                                 BitVector &PhysRegDefs,
4230b57cec5SDimitry Andric                                 BitVector &PhysRegClobbers,
4240b57cec5SDimitry Andric                                 SmallSet<int, 32> &StoredFIs,
4250b57cec5SDimitry Andric                                 SmallVectorImpl<CandidateInfo> &Candidates) {
4260b57cec5SDimitry Andric   bool RuledOut = false;
4270b57cec5SDimitry Andric   bool HasNonInvariantUse = false;
4280b57cec5SDimitry Andric   unsigned Def = 0;
4290b57cec5SDimitry Andric   for (const MachineOperand &MO : MI->operands()) {
4300b57cec5SDimitry Andric     if (MO.isFI()) {
4310b57cec5SDimitry Andric       // Remember if the instruction stores to the frame index.
4320b57cec5SDimitry Andric       int FI = MO.getIndex();
4330b57cec5SDimitry Andric       if (!StoredFIs.count(FI) &&
4340b57cec5SDimitry Andric           MFI->isSpillSlotObjectIndex(FI) &&
4350b57cec5SDimitry Andric           InstructionStoresToFI(MI, FI))
4360b57cec5SDimitry Andric         StoredFIs.insert(FI);
4370b57cec5SDimitry Andric       HasNonInvariantUse = true;
4380b57cec5SDimitry Andric       continue;
4390b57cec5SDimitry Andric     }
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric     // We can't hoist an instruction defining a physreg that is clobbered in
4420b57cec5SDimitry Andric     // the loop.
4430b57cec5SDimitry Andric     if (MO.isRegMask()) {
4440b57cec5SDimitry Andric       PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
4450b57cec5SDimitry Andric       continue;
4460b57cec5SDimitry Andric     }
4470b57cec5SDimitry Andric 
4480b57cec5SDimitry Andric     if (!MO.isReg())
4490b57cec5SDimitry Andric       continue;
4508bcb0991SDimitry Andric     Register Reg = MO.getReg();
4510b57cec5SDimitry Andric     if (!Reg)
4520b57cec5SDimitry Andric       continue;
4538bcb0991SDimitry Andric     assert(Register::isPhysicalRegister(Reg) &&
4540b57cec5SDimitry Andric            "Not expecting virtual register!");
4550b57cec5SDimitry Andric 
4560b57cec5SDimitry Andric     if (!MO.isDef()) {
4570b57cec5SDimitry Andric       if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
4580b57cec5SDimitry Andric         // If it's using a non-loop-invariant register, then it's obviously not
4590b57cec5SDimitry Andric         // safe to hoist.
4600b57cec5SDimitry Andric         HasNonInvariantUse = true;
4610b57cec5SDimitry Andric       continue;
4620b57cec5SDimitry Andric     }
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric     if (MO.isImplicit()) {
4650b57cec5SDimitry Andric       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
4660b57cec5SDimitry Andric         PhysRegClobbers.set(*AI);
4670b57cec5SDimitry Andric       if (!MO.isDead())
4680b57cec5SDimitry Andric         // Non-dead implicit def? This cannot be hoisted.
4690b57cec5SDimitry Andric         RuledOut = true;
4700b57cec5SDimitry Andric       // No need to check if a dead implicit def is also defined by
4710b57cec5SDimitry Andric       // another instruction.
4720b57cec5SDimitry Andric       continue;
4730b57cec5SDimitry Andric     }
4740b57cec5SDimitry Andric 
4750b57cec5SDimitry Andric     // FIXME: For now, avoid instructions with multiple defs, unless
4760b57cec5SDimitry Andric     // it's a dead implicit def.
4770b57cec5SDimitry Andric     if (Def)
4780b57cec5SDimitry Andric       RuledOut = true;
4790b57cec5SDimitry Andric     else
4800b57cec5SDimitry Andric       Def = Reg;
4810b57cec5SDimitry Andric 
4820b57cec5SDimitry Andric     // If we have already seen another instruction that defines the same
4830b57cec5SDimitry Andric     // register, then this is not safe.  Two defs is indicated by setting a
4840b57cec5SDimitry Andric     // PhysRegClobbers bit.
4850b57cec5SDimitry Andric     for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
4860b57cec5SDimitry Andric       if (PhysRegDefs.test(*AS))
4870b57cec5SDimitry Andric         PhysRegClobbers.set(*AS);
4880b57cec5SDimitry Andric     }
4890b57cec5SDimitry Andric     // Need a second loop because MCRegAliasIterator can visit the same
4900b57cec5SDimitry Andric     // register twice.
4910b57cec5SDimitry Andric     for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS)
4920b57cec5SDimitry Andric       PhysRegDefs.set(*AS);
4930b57cec5SDimitry Andric 
4940b57cec5SDimitry Andric     if (PhysRegClobbers.test(Reg))
4950b57cec5SDimitry Andric       // MI defined register is seen defined by another instruction in
4960b57cec5SDimitry Andric       // the loop, it cannot be a LICM candidate.
4970b57cec5SDimitry Andric       RuledOut = true;
4980b57cec5SDimitry Andric   }
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric   // Only consider reloads for now and remats which do not have register
5010b57cec5SDimitry Andric   // operands. FIXME: Consider unfold load folding instructions.
5020b57cec5SDimitry Andric   if (Def && !RuledOut) {
5030b57cec5SDimitry Andric     int FI = std::numeric_limits<int>::min();
5040b57cec5SDimitry Andric     if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
5050b57cec5SDimitry Andric         (TII->isLoadFromStackSlot(*MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
5060b57cec5SDimitry Andric       Candidates.push_back(CandidateInfo(MI, Def, FI));
5070b57cec5SDimitry Andric   }
5080b57cec5SDimitry Andric }
5090b57cec5SDimitry Andric 
5100b57cec5SDimitry Andric /// Walk the specified region of the CFG and hoist loop invariants out to the
5110b57cec5SDimitry Andric /// preheader.
HoistRegionPostRA()5120b57cec5SDimitry Andric void MachineLICMBase::HoistRegionPostRA() {
5130b57cec5SDimitry Andric   MachineBasicBlock *Preheader = getCurPreheader();
5140b57cec5SDimitry Andric   if (!Preheader)
5150b57cec5SDimitry Andric     return;
5160b57cec5SDimitry Andric 
5170b57cec5SDimitry Andric   unsigned NumRegs = TRI->getNumRegs();
5180b57cec5SDimitry Andric   BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
5190b57cec5SDimitry Andric   BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
5200b57cec5SDimitry Andric 
5210b57cec5SDimitry Andric   SmallVector<CandidateInfo, 32> Candidates;
5220b57cec5SDimitry Andric   SmallSet<int, 32> StoredFIs;
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric   // Walk the entire region, count number of defs for each register, and
5250b57cec5SDimitry Andric   // collect potential LICM candidates.
5260b57cec5SDimitry Andric   for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
5270b57cec5SDimitry Andric     // If the header of the loop containing this basic block is a landing pad,
5280b57cec5SDimitry Andric     // then don't try to hoist instructions out of this loop.
5290b57cec5SDimitry Andric     const MachineLoop *ML = MLI->getLoopFor(BB);
5300b57cec5SDimitry Andric     if (ML && ML->getHeader()->isEHPad()) continue;
5310b57cec5SDimitry Andric 
5320b57cec5SDimitry Andric     // Conservatively treat live-in's as an external def.
5330b57cec5SDimitry Andric     // FIXME: That means a reload that're reused in successor block(s) will not
5340b57cec5SDimitry Andric     // be LICM'ed.
5350b57cec5SDimitry Andric     for (const auto &LI : BB->liveins()) {
5360b57cec5SDimitry Andric       for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI)
5370b57cec5SDimitry Andric         PhysRegDefs.set(*AI);
5380b57cec5SDimitry Andric     }
5390b57cec5SDimitry Andric 
5400b57cec5SDimitry Andric     SpeculationState = SpeculateUnknown;
5410b57cec5SDimitry Andric     for (MachineInstr &MI : *BB)
5420b57cec5SDimitry Andric       ProcessMI(&MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
5430b57cec5SDimitry Andric   }
5440b57cec5SDimitry Andric 
5450b57cec5SDimitry Andric   // Gather the registers read / clobbered by the terminator.
5460b57cec5SDimitry Andric   BitVector TermRegs(NumRegs);
5470b57cec5SDimitry Andric   MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
5480b57cec5SDimitry Andric   if (TI != Preheader->end()) {
5490b57cec5SDimitry Andric     for (const MachineOperand &MO : TI->operands()) {
5500b57cec5SDimitry Andric       if (!MO.isReg())
5510b57cec5SDimitry Andric         continue;
5528bcb0991SDimitry Andric       Register Reg = MO.getReg();
5530b57cec5SDimitry Andric       if (!Reg)
5540b57cec5SDimitry Andric         continue;
5550b57cec5SDimitry Andric       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
5560b57cec5SDimitry Andric         TermRegs.set(*AI);
5570b57cec5SDimitry Andric     }
5580b57cec5SDimitry Andric   }
5590b57cec5SDimitry Andric 
5600b57cec5SDimitry Andric   // Now evaluate whether the potential candidates qualify.
5610b57cec5SDimitry Andric   // 1. Check if the candidate defined register is defined by another
5620b57cec5SDimitry Andric   //    instruction in the loop.
5630b57cec5SDimitry Andric   // 2. If the candidate is a load from stack slot (always true for now),
5640b57cec5SDimitry Andric   //    check if the slot is stored anywhere in the loop.
5650b57cec5SDimitry Andric   // 3. Make sure candidate def should not clobber
5660b57cec5SDimitry Andric   //    registers read by the terminator. Similarly its def should not be
5670b57cec5SDimitry Andric   //    clobbered by the terminator.
5680b57cec5SDimitry Andric   for (CandidateInfo &Candidate : Candidates) {
5690b57cec5SDimitry Andric     if (Candidate.FI != std::numeric_limits<int>::min() &&
5700b57cec5SDimitry Andric         StoredFIs.count(Candidate.FI))
5710b57cec5SDimitry Andric       continue;
5720b57cec5SDimitry Andric 
5730b57cec5SDimitry Andric     unsigned Def = Candidate.Def;
5740b57cec5SDimitry Andric     if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
5750b57cec5SDimitry Andric       bool Safe = true;
5760b57cec5SDimitry Andric       MachineInstr *MI = Candidate.MI;
5770b57cec5SDimitry Andric       for (const MachineOperand &MO : MI->operands()) {
5780b57cec5SDimitry Andric         if (!MO.isReg() || MO.isDef() || !MO.getReg())
5790b57cec5SDimitry Andric           continue;
5808bcb0991SDimitry Andric         Register Reg = MO.getReg();
5810b57cec5SDimitry Andric         if (PhysRegDefs.test(Reg) ||
5820b57cec5SDimitry Andric             PhysRegClobbers.test(Reg)) {
5830b57cec5SDimitry Andric           // If it's using a non-loop-invariant register, then it's obviously
5840b57cec5SDimitry Andric           // not safe to hoist.
5850b57cec5SDimitry Andric           Safe = false;
5860b57cec5SDimitry Andric           break;
5870b57cec5SDimitry Andric         }
5880b57cec5SDimitry Andric       }
5890b57cec5SDimitry Andric       if (Safe)
5900b57cec5SDimitry Andric         HoistPostRA(MI, Candidate.Def);
5910b57cec5SDimitry Andric     }
5920b57cec5SDimitry Andric   }
5930b57cec5SDimitry Andric }
5940b57cec5SDimitry Andric 
5950b57cec5SDimitry Andric /// Add register 'Reg' to the livein sets of BBs in the current loop, and make
5960b57cec5SDimitry Andric /// sure it is not killed by any instructions in the loop.
AddToLiveIns(MCRegister Reg)597af732203SDimitry Andric void MachineLICMBase::AddToLiveIns(MCRegister Reg) {
5980b57cec5SDimitry Andric   for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
5990b57cec5SDimitry Andric     if (!BB->isLiveIn(Reg))
6000b57cec5SDimitry Andric       BB->addLiveIn(Reg);
6010b57cec5SDimitry Andric     for (MachineInstr &MI : *BB) {
6020b57cec5SDimitry Andric       for (MachineOperand &MO : MI.operands()) {
6030b57cec5SDimitry Andric         if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
6040b57cec5SDimitry Andric         if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
6050b57cec5SDimitry Andric           MO.setIsKill(false);
6060b57cec5SDimitry Andric       }
6070b57cec5SDimitry Andric     }
6080b57cec5SDimitry Andric   }
6090b57cec5SDimitry Andric }
6100b57cec5SDimitry Andric 
6110b57cec5SDimitry Andric /// When an instruction is found to only use loop invariant operands that is
6120b57cec5SDimitry Andric /// safe to hoist, this instruction is called to do the dirty work.
HoistPostRA(MachineInstr * MI,unsigned Def)6130b57cec5SDimitry Andric void MachineLICMBase::HoistPostRA(MachineInstr *MI, unsigned Def) {
6140b57cec5SDimitry Andric   MachineBasicBlock *Preheader = getCurPreheader();
6150b57cec5SDimitry Andric 
6160b57cec5SDimitry Andric   // Now move the instructions to the predecessor, inserting it before any
6170b57cec5SDimitry Andric   // terminator instructions.
6180b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Hoisting to " << printMBBReference(*Preheader)
6190b57cec5SDimitry Andric                     << " from " << printMBBReference(*MI->getParent()) << ": "
6200b57cec5SDimitry Andric                     << *MI);
6210b57cec5SDimitry Andric 
6220b57cec5SDimitry Andric   // Splice the instruction to the preheader.
6230b57cec5SDimitry Andric   MachineBasicBlock *MBB = MI->getParent();
6240b57cec5SDimitry Andric   Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
6250b57cec5SDimitry Andric 
6265ffd83dbSDimitry Andric   // Since we are moving the instruction out of its basic block, we do not
6275ffd83dbSDimitry Andric   // retain its debug location. Doing so would degrade the debugging
6285ffd83dbSDimitry Andric   // experience and adversely affect the accuracy of profiling information.
6295ffd83dbSDimitry Andric   assert(!MI->isDebugInstr() && "Should not hoist debug inst");
6305ffd83dbSDimitry Andric   MI->setDebugLoc(DebugLoc());
6315ffd83dbSDimitry Andric 
6320b57cec5SDimitry Andric   // Add register to livein list to all the BBs in the current loop since a
6330b57cec5SDimitry Andric   // loop invariant must be kept live throughout the whole loop. This is
6340b57cec5SDimitry Andric   // important to ensure later passes do not scavenge the def register.
6350b57cec5SDimitry Andric   AddToLiveIns(Def);
6360b57cec5SDimitry Andric 
6370b57cec5SDimitry Andric   ++NumPostRAHoisted;
6380b57cec5SDimitry Andric   Changed = true;
6390b57cec5SDimitry Andric }
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric /// Check if this mbb is guaranteed to execute. If not then a load from this mbb
6420b57cec5SDimitry Andric /// may not be safe to hoist.
IsGuaranteedToExecute(MachineBasicBlock * BB)6430b57cec5SDimitry Andric bool MachineLICMBase::IsGuaranteedToExecute(MachineBasicBlock *BB) {
6440b57cec5SDimitry Andric   if (SpeculationState != SpeculateUnknown)
6450b57cec5SDimitry Andric     return SpeculationState == SpeculateFalse;
6460b57cec5SDimitry Andric 
6470b57cec5SDimitry Andric   if (BB != CurLoop->getHeader()) {
6480b57cec5SDimitry Andric     // Check loop exiting blocks.
6490b57cec5SDimitry Andric     SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
6500b57cec5SDimitry Andric     CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
6510b57cec5SDimitry Andric     for (MachineBasicBlock *CurrentLoopExitingBlock : CurrentLoopExitingBlocks)
6520b57cec5SDimitry Andric       if (!DT->dominates(BB, CurrentLoopExitingBlock)) {
6530b57cec5SDimitry Andric         SpeculationState = SpeculateTrue;
6540b57cec5SDimitry Andric         return false;
6550b57cec5SDimitry Andric       }
6560b57cec5SDimitry Andric   }
6570b57cec5SDimitry Andric 
6580b57cec5SDimitry Andric   SpeculationState = SpeculateFalse;
6590b57cec5SDimitry Andric   return true;
6600b57cec5SDimitry Andric }
6610b57cec5SDimitry Andric 
EnterScope(MachineBasicBlock * MBB)6620b57cec5SDimitry Andric void MachineLICMBase::EnterScope(MachineBasicBlock *MBB) {
6630b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Entering " << printMBBReference(*MBB) << '\n');
6640b57cec5SDimitry Andric 
6650b57cec5SDimitry Andric   // Remember livein register pressure.
6660b57cec5SDimitry Andric   BackTrace.push_back(RegPressure);
6670b57cec5SDimitry Andric }
6680b57cec5SDimitry Andric 
ExitScope(MachineBasicBlock * MBB)6690b57cec5SDimitry Andric void MachineLICMBase::ExitScope(MachineBasicBlock *MBB) {
6700b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Exiting " << printMBBReference(*MBB) << '\n');
6710b57cec5SDimitry Andric   BackTrace.pop_back();
6720b57cec5SDimitry Andric }
6730b57cec5SDimitry Andric 
6740b57cec5SDimitry Andric /// Destroy scope for the MBB that corresponds to the given dominator tree node
6750b57cec5SDimitry Andric /// if its a leaf or all of its children are done. Walk up the dominator tree to
6760b57cec5SDimitry Andric /// destroy ancestors which are now done.
ExitScopeIfDone(MachineDomTreeNode * Node,DenseMap<MachineDomTreeNode *,unsigned> & OpenChildren,DenseMap<MachineDomTreeNode *,MachineDomTreeNode * > & ParentMap)6770b57cec5SDimitry Andric void MachineLICMBase::ExitScopeIfDone(MachineDomTreeNode *Node,
6780b57cec5SDimitry Andric     DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
6790b57cec5SDimitry Andric     DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
6800b57cec5SDimitry Andric   if (OpenChildren[Node])
6810b57cec5SDimitry Andric     return;
6820b57cec5SDimitry Andric 
6830b57cec5SDimitry Andric   // Pop scope.
6840b57cec5SDimitry Andric   ExitScope(Node->getBlock());
6850b57cec5SDimitry Andric 
6860b57cec5SDimitry Andric   // Now traverse upwards to pop ancestors whose offsprings are all done.
6870b57cec5SDimitry Andric   while (MachineDomTreeNode *Parent = ParentMap[Node]) {
6880b57cec5SDimitry Andric     unsigned Left = --OpenChildren[Parent];
6890b57cec5SDimitry Andric     if (Left != 0)
6900b57cec5SDimitry Andric       break;
6910b57cec5SDimitry Andric     ExitScope(Parent->getBlock());
6920b57cec5SDimitry Andric     Node = Parent;
6930b57cec5SDimitry Andric   }
6940b57cec5SDimitry Andric }
6950b57cec5SDimitry Andric 
6960b57cec5SDimitry Andric /// Walk the specified loop in the CFG (defined by all blocks dominated by the
6970b57cec5SDimitry Andric /// specified header block, and that are in the current loop) in depth first
6980b57cec5SDimitry Andric /// order w.r.t the DominatorTree. This allows us to visit definitions before
6990b57cec5SDimitry Andric /// uses, allowing us to hoist a loop body in one pass without iteration.
HoistOutOfLoop(MachineDomTreeNode * HeaderN)7000b57cec5SDimitry Andric void MachineLICMBase::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
7010b57cec5SDimitry Andric   MachineBasicBlock *Preheader = getCurPreheader();
7020b57cec5SDimitry Andric   if (!Preheader)
7030b57cec5SDimitry Andric     return;
7040b57cec5SDimitry Andric 
7050b57cec5SDimitry Andric   SmallVector<MachineDomTreeNode*, 32> Scopes;
7060b57cec5SDimitry Andric   SmallVector<MachineDomTreeNode*, 8> WorkList;
7070b57cec5SDimitry Andric   DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
7080b57cec5SDimitry Andric   DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
7090b57cec5SDimitry Andric 
7100b57cec5SDimitry Andric   // Perform a DFS walk to determine the order of visit.
7110b57cec5SDimitry Andric   WorkList.push_back(HeaderN);
7120b57cec5SDimitry Andric   while (!WorkList.empty()) {
7130b57cec5SDimitry Andric     MachineDomTreeNode *Node = WorkList.pop_back_val();
7140b57cec5SDimitry Andric     assert(Node && "Null dominator tree node?");
7150b57cec5SDimitry Andric     MachineBasicBlock *BB = Node->getBlock();
7160b57cec5SDimitry Andric 
7170b57cec5SDimitry Andric     // If the header of the loop containing this basic block is a landing pad,
7180b57cec5SDimitry Andric     // then don't try to hoist instructions out of this loop.
7190b57cec5SDimitry Andric     const MachineLoop *ML = MLI->getLoopFor(BB);
7200b57cec5SDimitry Andric     if (ML && ML->getHeader()->isEHPad())
7210b57cec5SDimitry Andric       continue;
7220b57cec5SDimitry Andric 
7230b57cec5SDimitry Andric     // If this subregion is not in the top level loop at all, exit.
7240b57cec5SDimitry Andric     if (!CurLoop->contains(BB))
7250b57cec5SDimitry Andric       continue;
7260b57cec5SDimitry Andric 
7270b57cec5SDimitry Andric     Scopes.push_back(Node);
7285ffd83dbSDimitry Andric     unsigned NumChildren = Node->getNumChildren();
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric     // Don't hoist things out of a large switch statement.  This often causes
7310b57cec5SDimitry Andric     // code to be hoisted that wasn't going to be executed, and increases
7320b57cec5SDimitry Andric     // register pressure in a situation where it's likely to matter.
7330b57cec5SDimitry Andric     if (BB->succ_size() >= 25)
7340b57cec5SDimitry Andric       NumChildren = 0;
7350b57cec5SDimitry Andric 
7360b57cec5SDimitry Andric     OpenChildren[Node] = NumChildren;
7375ffd83dbSDimitry Andric     if (NumChildren) {
7380b57cec5SDimitry Andric       // Add children in reverse order as then the next popped worklist node is
7390b57cec5SDimitry Andric       // the first child of this node.  This means we ultimately traverse the
7400b57cec5SDimitry Andric       // DOM tree in exactly the same order as if we'd recursed.
7415ffd83dbSDimitry Andric       for (MachineDomTreeNode *Child : reverse(Node->children())) {
7420b57cec5SDimitry Andric         ParentMap[Child] = Node;
7430b57cec5SDimitry Andric         WorkList.push_back(Child);
7440b57cec5SDimitry Andric       }
7450b57cec5SDimitry Andric     }
7465ffd83dbSDimitry Andric   }
7470b57cec5SDimitry Andric 
7480b57cec5SDimitry Andric   if (Scopes.size() == 0)
7490b57cec5SDimitry Andric     return;
7500b57cec5SDimitry Andric 
7510b57cec5SDimitry Andric   // Compute registers which are livein into the loop headers.
7520b57cec5SDimitry Andric   RegSeen.clear();
7530b57cec5SDimitry Andric   BackTrace.clear();
7540b57cec5SDimitry Andric   InitRegPressure(Preheader);
7550b57cec5SDimitry Andric 
7560b57cec5SDimitry Andric   // Now perform LICM.
7570b57cec5SDimitry Andric   for (MachineDomTreeNode *Node : Scopes) {
7580b57cec5SDimitry Andric     MachineBasicBlock *MBB = Node->getBlock();
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric     EnterScope(MBB);
7610b57cec5SDimitry Andric 
7620b57cec5SDimitry Andric     // Process the block
7630b57cec5SDimitry Andric     SpeculationState = SpeculateUnknown;
7640b57cec5SDimitry Andric     for (MachineBasicBlock::iterator
7650b57cec5SDimitry Andric          MII = MBB->begin(), E = MBB->end(); MII != E; ) {
7660b57cec5SDimitry Andric       MachineBasicBlock::iterator NextMII = MII; ++NextMII;
7670b57cec5SDimitry Andric       MachineInstr *MI = &*MII;
7680b57cec5SDimitry Andric       if (!Hoist(MI, Preheader))
7690b57cec5SDimitry Andric         UpdateRegPressure(MI);
7700b57cec5SDimitry Andric       // If we have hoisted an instruction that may store, it can only be a
7710b57cec5SDimitry Andric       // constant store.
7720b57cec5SDimitry Andric       MII = NextMII;
7730b57cec5SDimitry Andric     }
7740b57cec5SDimitry Andric 
7750b57cec5SDimitry Andric     // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
7760b57cec5SDimitry Andric     ExitScopeIfDone(Node, OpenChildren, ParentMap);
7770b57cec5SDimitry Andric   }
7780b57cec5SDimitry Andric }
7790b57cec5SDimitry Andric 
isOperandKill(const MachineOperand & MO,MachineRegisterInfo * MRI)7800b57cec5SDimitry Andric static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
7810b57cec5SDimitry Andric   return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
7820b57cec5SDimitry Andric }
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric /// Find all virtual register references that are liveout of the preheader to
7850b57cec5SDimitry Andric /// initialize the starting "register pressure". Note this does not count live
7860b57cec5SDimitry Andric /// through (livein but not used) registers.
InitRegPressure(MachineBasicBlock * BB)7870b57cec5SDimitry Andric void MachineLICMBase::InitRegPressure(MachineBasicBlock *BB) {
7880b57cec5SDimitry Andric   std::fill(RegPressure.begin(), RegPressure.end(), 0);
7890b57cec5SDimitry Andric 
7900b57cec5SDimitry Andric   // If the preheader has only a single predecessor and it ends with a
7910b57cec5SDimitry Andric   // fallthrough or an unconditional branch, then scan its predecessor for live
7920b57cec5SDimitry Andric   // defs as well. This happens whenever the preheader is created by splitting
7930b57cec5SDimitry Andric   // the critical edge from the loop predecessor to the loop header.
7940b57cec5SDimitry Andric   if (BB->pred_size() == 1) {
7950b57cec5SDimitry Andric     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
7960b57cec5SDimitry Andric     SmallVector<MachineOperand, 4> Cond;
7970b57cec5SDimitry Andric     if (!TII->analyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
7980b57cec5SDimitry Andric       InitRegPressure(*BB->pred_begin());
7990b57cec5SDimitry Andric   }
8000b57cec5SDimitry Andric 
8010b57cec5SDimitry Andric   for (const MachineInstr &MI : *BB)
8020b57cec5SDimitry Andric     UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
8030b57cec5SDimitry Andric }
8040b57cec5SDimitry Andric 
8050b57cec5SDimitry Andric /// Update estimate of register pressure after the specified instruction.
UpdateRegPressure(const MachineInstr * MI,bool ConsiderUnseenAsDef)8060b57cec5SDimitry Andric void MachineLICMBase::UpdateRegPressure(const MachineInstr *MI,
8070b57cec5SDimitry Andric                                         bool ConsiderUnseenAsDef) {
8080b57cec5SDimitry Andric   auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
8090b57cec5SDimitry Andric   for (const auto &RPIdAndCost : Cost) {
8100b57cec5SDimitry Andric     unsigned Class = RPIdAndCost.first;
8110b57cec5SDimitry Andric     if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second)
8120b57cec5SDimitry Andric       RegPressure[Class] = 0;
8130b57cec5SDimitry Andric     else
8140b57cec5SDimitry Andric       RegPressure[Class] += RPIdAndCost.second;
8150b57cec5SDimitry Andric   }
8160b57cec5SDimitry Andric }
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric /// Calculate the additional register pressure that the registers used in MI
8190b57cec5SDimitry Andric /// cause.
8200b57cec5SDimitry Andric ///
8210b57cec5SDimitry Andric /// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
8220b57cec5SDimitry Andric /// figure out which usages are live-ins.
8230b57cec5SDimitry Andric /// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
8240b57cec5SDimitry Andric DenseMap<unsigned, int>
calcRegisterCost(const MachineInstr * MI,bool ConsiderSeen,bool ConsiderUnseenAsDef)8250b57cec5SDimitry Andric MachineLICMBase::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
8260b57cec5SDimitry Andric                                   bool ConsiderUnseenAsDef) {
8270b57cec5SDimitry Andric   DenseMap<unsigned, int> Cost;
8280b57cec5SDimitry Andric   if (MI->isImplicitDef())
8290b57cec5SDimitry Andric     return Cost;
8300b57cec5SDimitry Andric   for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
8310b57cec5SDimitry Andric     const MachineOperand &MO = MI->getOperand(i);
8320b57cec5SDimitry Andric     if (!MO.isReg() || MO.isImplicit())
8330b57cec5SDimitry Andric       continue;
8348bcb0991SDimitry Andric     Register Reg = MO.getReg();
8358bcb0991SDimitry Andric     if (!Register::isVirtualRegister(Reg))
8360b57cec5SDimitry Andric       continue;
8370b57cec5SDimitry Andric 
8380b57cec5SDimitry Andric     // FIXME: It seems bad to use RegSeen only for some of these calculations.
8390b57cec5SDimitry Andric     bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
8400b57cec5SDimitry Andric     const TargetRegisterClass *RC = MRI->getRegClass(Reg);
8410b57cec5SDimitry Andric 
8420b57cec5SDimitry Andric     RegClassWeight W = TRI->getRegClassWeight(RC);
8430b57cec5SDimitry Andric     int RCCost = 0;
8440b57cec5SDimitry Andric     if (MO.isDef())
8450b57cec5SDimitry Andric       RCCost = W.RegWeight;
8460b57cec5SDimitry Andric     else {
8470b57cec5SDimitry Andric       bool isKill = isOperandKill(MO, MRI);
8480b57cec5SDimitry Andric       if (isNew && !isKill && ConsiderUnseenAsDef)
8490b57cec5SDimitry Andric         // Haven't seen this, it must be a livein.
8500b57cec5SDimitry Andric         RCCost = W.RegWeight;
8510b57cec5SDimitry Andric       else if (!isNew && isKill)
8520b57cec5SDimitry Andric         RCCost = -W.RegWeight;
8530b57cec5SDimitry Andric     }
8540b57cec5SDimitry Andric     if (RCCost == 0)
8550b57cec5SDimitry Andric       continue;
8560b57cec5SDimitry Andric     const int *PS = TRI->getRegClassPressureSets(RC);
8570b57cec5SDimitry Andric     for (; *PS != -1; ++PS) {
8580b57cec5SDimitry Andric       if (Cost.find(*PS) == Cost.end())
8590b57cec5SDimitry Andric         Cost[*PS] = RCCost;
8600b57cec5SDimitry Andric       else
8610b57cec5SDimitry Andric         Cost[*PS] += RCCost;
8620b57cec5SDimitry Andric     }
8630b57cec5SDimitry Andric   }
8640b57cec5SDimitry Andric   return Cost;
8650b57cec5SDimitry Andric }
8660b57cec5SDimitry Andric 
8670b57cec5SDimitry Andric /// Return true if this machine instruction loads from global offset table or
8680b57cec5SDimitry Andric /// constant pool.
mayLoadFromGOTOrConstantPool(MachineInstr & MI)8690b57cec5SDimitry Andric static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
8700b57cec5SDimitry Andric   assert(MI.mayLoad() && "Expected MI that loads!");
8710b57cec5SDimitry Andric 
8720b57cec5SDimitry Andric   // If we lost memory operands, conservatively assume that the instruction
8730b57cec5SDimitry Andric   // reads from everything..
8740b57cec5SDimitry Andric   if (MI.memoperands_empty())
8750b57cec5SDimitry Andric     return true;
8760b57cec5SDimitry Andric 
8770b57cec5SDimitry Andric   for (MachineMemOperand *MemOp : MI.memoperands())
8780b57cec5SDimitry Andric     if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
8790b57cec5SDimitry Andric       if (PSV->isGOT() || PSV->isConstantPool())
8800b57cec5SDimitry Andric         return true;
8810b57cec5SDimitry Andric 
8820b57cec5SDimitry Andric   return false;
8830b57cec5SDimitry Andric }
8840b57cec5SDimitry Andric 
8850b57cec5SDimitry Andric // This function iterates through all the operands of the input store MI and
8860b57cec5SDimitry Andric // checks that each register operand statisfies isCallerPreservedPhysReg.
8870b57cec5SDimitry Andric // This means, the value being stored and the address where it is being stored
8880b57cec5SDimitry Andric // is constant throughout the body of the function (not including prologue and
8890b57cec5SDimitry Andric // epilogue). When called with an MI that isn't a store, it returns false.
8900b57cec5SDimitry Andric // A future improvement can be to check if the store registers are constant
8910b57cec5SDimitry Andric // throughout the loop rather than throughout the funtion.
isInvariantStore(const MachineInstr & MI,const TargetRegisterInfo * TRI,const MachineRegisterInfo * MRI)8920b57cec5SDimitry Andric static bool isInvariantStore(const MachineInstr &MI,
8930b57cec5SDimitry Andric                              const TargetRegisterInfo *TRI,
8940b57cec5SDimitry Andric                              const MachineRegisterInfo *MRI) {
8950b57cec5SDimitry Andric 
8960b57cec5SDimitry Andric   bool FoundCallerPresReg = false;
8970b57cec5SDimitry Andric   if (!MI.mayStore() || MI.hasUnmodeledSideEffects() ||
8980b57cec5SDimitry Andric       (MI.getNumOperands() == 0))
8990b57cec5SDimitry Andric     return false;
9000b57cec5SDimitry Andric 
9010b57cec5SDimitry Andric   // Check that all register operands are caller-preserved physical registers.
9020b57cec5SDimitry Andric   for (const MachineOperand &MO : MI.operands()) {
9030b57cec5SDimitry Andric     if (MO.isReg()) {
9048bcb0991SDimitry Andric       Register Reg = MO.getReg();
9050b57cec5SDimitry Andric       // If operand is a virtual register, check if it comes from a copy of a
9060b57cec5SDimitry Andric       // physical register.
9078bcb0991SDimitry Andric       if (Register::isVirtualRegister(Reg))
9080b57cec5SDimitry Andric         Reg = TRI->lookThruCopyLike(MO.getReg(), MRI);
9098bcb0991SDimitry Andric       if (Register::isVirtualRegister(Reg))
9100b57cec5SDimitry Andric         return false;
911af732203SDimitry Andric       if (!TRI->isCallerPreservedPhysReg(Reg.asMCReg(), *MI.getMF()))
9120b57cec5SDimitry Andric         return false;
9130b57cec5SDimitry Andric       else
9140b57cec5SDimitry Andric         FoundCallerPresReg = true;
9150b57cec5SDimitry Andric     } else if (!MO.isImm()) {
9160b57cec5SDimitry Andric         return false;
9170b57cec5SDimitry Andric     }
9180b57cec5SDimitry Andric   }
9190b57cec5SDimitry Andric   return FoundCallerPresReg;
9200b57cec5SDimitry Andric }
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric // Return true if the input MI is a copy instruction that feeds an invariant
9230b57cec5SDimitry Andric // store instruction. This means that the src of the copy has to satisfy
9240b57cec5SDimitry Andric // isCallerPreservedPhysReg and atleast one of it's users should satisfy
9250b57cec5SDimitry Andric // isInvariantStore.
isCopyFeedingInvariantStore(const MachineInstr & MI,const MachineRegisterInfo * MRI,const TargetRegisterInfo * TRI)9260b57cec5SDimitry Andric static bool isCopyFeedingInvariantStore(const MachineInstr &MI,
9270b57cec5SDimitry Andric                                         const MachineRegisterInfo *MRI,
9280b57cec5SDimitry Andric                                         const TargetRegisterInfo *TRI) {
9290b57cec5SDimitry Andric 
9300b57cec5SDimitry Andric   // FIXME: If targets would like to look through instructions that aren't
9310b57cec5SDimitry Andric   // pure copies, this can be updated to a query.
9320b57cec5SDimitry Andric   if (!MI.isCopy())
9330b57cec5SDimitry Andric     return false;
9340b57cec5SDimitry Andric 
9350b57cec5SDimitry Andric   const MachineFunction *MF = MI.getMF();
9360b57cec5SDimitry Andric   // Check that we are copying a constant physical register.
9378bcb0991SDimitry Andric   Register CopySrcReg = MI.getOperand(1).getReg();
9388bcb0991SDimitry Andric   if (Register::isVirtualRegister(CopySrcReg))
9390b57cec5SDimitry Andric     return false;
9400b57cec5SDimitry Andric 
941af732203SDimitry Andric   if (!TRI->isCallerPreservedPhysReg(CopySrcReg.asMCReg(), *MF))
9420b57cec5SDimitry Andric     return false;
9430b57cec5SDimitry Andric 
9448bcb0991SDimitry Andric   Register CopyDstReg = MI.getOperand(0).getReg();
9450b57cec5SDimitry Andric   // Check if any of the uses of the copy are invariant stores.
9468bcb0991SDimitry Andric   assert(Register::isVirtualRegister(CopyDstReg) &&
9470b57cec5SDimitry Andric          "copy dst is not a virtual reg");
9480b57cec5SDimitry Andric 
9490b57cec5SDimitry Andric   for (MachineInstr &UseMI : MRI->use_instructions(CopyDstReg)) {
9500b57cec5SDimitry Andric     if (UseMI.mayStore() && isInvariantStore(UseMI, TRI, MRI))
9510b57cec5SDimitry Andric       return true;
9520b57cec5SDimitry Andric   }
9530b57cec5SDimitry Andric   return false;
9540b57cec5SDimitry Andric }
9550b57cec5SDimitry Andric 
9560b57cec5SDimitry Andric /// Returns true if the instruction may be a suitable candidate for LICM.
9570b57cec5SDimitry Andric /// e.g. If the instruction is a call, then it's obviously not safe to hoist it.
IsLICMCandidate(MachineInstr & I)9580b57cec5SDimitry Andric bool MachineLICMBase::IsLICMCandidate(MachineInstr &I) {
9590b57cec5SDimitry Andric   // Check if it's safe to move the instruction.
9600b57cec5SDimitry Andric   bool DontMoveAcrossStore = true;
9610b57cec5SDimitry Andric   if ((!I.isSafeToMove(AA, DontMoveAcrossStore)) &&
9620b57cec5SDimitry Andric       !(HoistConstStores && isInvariantStore(I, TRI, MRI))) {
963af732203SDimitry Andric     LLVM_DEBUG(dbgs() << "LICM: Instruction not safe to move.\n");
9640b57cec5SDimitry Andric     return false;
9650b57cec5SDimitry Andric   }
9660b57cec5SDimitry Andric 
967*5f7ddb14SDimitry Andric   // If it is a load then check if it is guaranteed to execute by making sure
968*5f7ddb14SDimitry Andric   // that it dominates all exiting blocks. If it doesn't, then there is a path
969*5f7ddb14SDimitry Andric   // out of the loop which does not execute this load, so we can't hoist it.
970*5f7ddb14SDimitry Andric   // Loads from constant memory are safe to speculate, for example indexed load
971*5f7ddb14SDimitry Andric   // from a jump table.
9720b57cec5SDimitry Andric   // Stores and side effects are already checked by isSafeToMove.
9730b57cec5SDimitry Andric   if (I.mayLoad() && !mayLoadFromGOTOrConstantPool(I) &&
974af732203SDimitry Andric       !IsGuaranteedToExecute(I.getParent())) {
975af732203SDimitry Andric     LLVM_DEBUG(dbgs() << "LICM: Load not guaranteed to execute.\n");
976af732203SDimitry Andric     return false;
977af732203SDimitry Andric   }
978af732203SDimitry Andric 
979af732203SDimitry Andric   // Convergent attribute has been used on operations that involve inter-thread
980af732203SDimitry Andric   // communication which results are implicitly affected by the enclosing
981af732203SDimitry Andric   // control flows. It is not safe to hoist or sink such operations across
982af732203SDimitry Andric   // control flow.
983af732203SDimitry Andric   if (I.isConvergent())
9840b57cec5SDimitry Andric     return false;
9850b57cec5SDimitry Andric 
9860b57cec5SDimitry Andric   return true;
9870b57cec5SDimitry Andric }
9880b57cec5SDimitry Andric 
9890b57cec5SDimitry Andric /// Returns true if the instruction is loop invariant.
IsLoopInvariantInst(MachineInstr & I)9900b57cec5SDimitry Andric bool MachineLICMBase::IsLoopInvariantInst(MachineInstr &I) {
991af732203SDimitry Andric   if (!IsLICMCandidate(I)) {
992af732203SDimitry Andric     LLVM_DEBUG(dbgs() << "LICM: Instruction not a LICM candidate\n");
9930b57cec5SDimitry Andric     return false;
9940b57cec5SDimitry Andric   }
995af732203SDimitry Andric   return CurLoop->isLoopInvariant(I);
9960b57cec5SDimitry Andric }
9970b57cec5SDimitry Andric 
9980b57cec5SDimitry Andric /// Return true if the specified instruction is used by a phi node and hoisting
9990b57cec5SDimitry Andric /// it could cause a copy to be inserted.
HasLoopPHIUse(const MachineInstr * MI) const10000b57cec5SDimitry Andric bool MachineLICMBase::HasLoopPHIUse(const MachineInstr *MI) const {
10010b57cec5SDimitry Andric   SmallVector<const MachineInstr*, 8> Work(1, MI);
10020b57cec5SDimitry Andric   do {
10030b57cec5SDimitry Andric     MI = Work.pop_back_val();
10040b57cec5SDimitry Andric     for (const MachineOperand &MO : MI->operands()) {
10050b57cec5SDimitry Andric       if (!MO.isReg() || !MO.isDef())
10060b57cec5SDimitry Andric         continue;
10078bcb0991SDimitry Andric       Register Reg = MO.getReg();
10088bcb0991SDimitry Andric       if (!Register::isVirtualRegister(Reg))
10090b57cec5SDimitry Andric         continue;
10100b57cec5SDimitry Andric       for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
10110b57cec5SDimitry Andric         // A PHI may cause a copy to be inserted.
10120b57cec5SDimitry Andric         if (UseMI.isPHI()) {
10130b57cec5SDimitry Andric           // A PHI inside the loop causes a copy because the live range of Reg is
10140b57cec5SDimitry Andric           // extended across the PHI.
10150b57cec5SDimitry Andric           if (CurLoop->contains(&UseMI))
10160b57cec5SDimitry Andric             return true;
10170b57cec5SDimitry Andric           // A PHI in an exit block can cause a copy to be inserted if the PHI
10180b57cec5SDimitry Andric           // has multiple predecessors in the loop with different values.
10190b57cec5SDimitry Andric           // For now, approximate by rejecting all exit blocks.
10200b57cec5SDimitry Andric           if (isExitBlock(UseMI.getParent()))
10210b57cec5SDimitry Andric             return true;
10220b57cec5SDimitry Andric           continue;
10230b57cec5SDimitry Andric         }
10240b57cec5SDimitry Andric         // Look past copies as well.
10250b57cec5SDimitry Andric         if (UseMI.isCopy() && CurLoop->contains(&UseMI))
10260b57cec5SDimitry Andric           Work.push_back(&UseMI);
10270b57cec5SDimitry Andric       }
10280b57cec5SDimitry Andric     }
10290b57cec5SDimitry Andric   } while (!Work.empty());
10300b57cec5SDimitry Andric   return false;
10310b57cec5SDimitry Andric }
10320b57cec5SDimitry Andric 
10330b57cec5SDimitry Andric /// Compute operand latency between a def of 'Reg' and an use in the current
10340b57cec5SDimitry Andric /// loop, return true if the target considered it high.
HasHighOperandLatency(MachineInstr & MI,unsigned DefIdx,Register Reg) const1035af732203SDimitry Andric bool MachineLICMBase::HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
1036af732203SDimitry Andric                                             Register Reg) const {
10370b57cec5SDimitry Andric   if (MRI->use_nodbg_empty(Reg))
10380b57cec5SDimitry Andric     return false;
10390b57cec5SDimitry Andric 
10400b57cec5SDimitry Andric   for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
10410b57cec5SDimitry Andric     if (UseMI.isCopyLike())
10420b57cec5SDimitry Andric       continue;
10430b57cec5SDimitry Andric     if (!CurLoop->contains(UseMI.getParent()))
10440b57cec5SDimitry Andric       continue;
10450b57cec5SDimitry Andric     for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
10460b57cec5SDimitry Andric       const MachineOperand &MO = UseMI.getOperand(i);
10470b57cec5SDimitry Andric       if (!MO.isReg() || !MO.isUse())
10480b57cec5SDimitry Andric         continue;
10498bcb0991SDimitry Andric       Register MOReg = MO.getReg();
10500b57cec5SDimitry Andric       if (MOReg != Reg)
10510b57cec5SDimitry Andric         continue;
10520b57cec5SDimitry Andric 
10530b57cec5SDimitry Andric       if (TII->hasHighOperandLatency(SchedModel, MRI, MI, DefIdx, UseMI, i))
10540b57cec5SDimitry Andric         return true;
10550b57cec5SDimitry Andric     }
10560b57cec5SDimitry Andric 
10570b57cec5SDimitry Andric     // Only look at the first in loop use.
10580b57cec5SDimitry Andric     break;
10590b57cec5SDimitry Andric   }
10600b57cec5SDimitry Andric 
10610b57cec5SDimitry Andric   return false;
10620b57cec5SDimitry Andric }
10630b57cec5SDimitry Andric 
10640b57cec5SDimitry Andric /// Return true if the instruction is marked "cheap" or the operand latency
10650b57cec5SDimitry Andric /// between its def and a use is one or less.
IsCheapInstruction(MachineInstr & MI) const10660b57cec5SDimitry Andric bool MachineLICMBase::IsCheapInstruction(MachineInstr &MI) const {
10670b57cec5SDimitry Andric   if (TII->isAsCheapAsAMove(MI) || MI.isCopyLike())
10680b57cec5SDimitry Andric     return true;
10690b57cec5SDimitry Andric 
10700b57cec5SDimitry Andric   bool isCheap = false;
10710b57cec5SDimitry Andric   unsigned NumDefs = MI.getDesc().getNumDefs();
10720b57cec5SDimitry Andric   for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
10730b57cec5SDimitry Andric     MachineOperand &DefMO = MI.getOperand(i);
10740b57cec5SDimitry Andric     if (!DefMO.isReg() || !DefMO.isDef())
10750b57cec5SDimitry Andric       continue;
10760b57cec5SDimitry Andric     --NumDefs;
10778bcb0991SDimitry Andric     Register Reg = DefMO.getReg();
10788bcb0991SDimitry Andric     if (Register::isPhysicalRegister(Reg))
10790b57cec5SDimitry Andric       continue;
10800b57cec5SDimitry Andric 
10810b57cec5SDimitry Andric     if (!TII->hasLowDefLatency(SchedModel, MI, i))
10820b57cec5SDimitry Andric       return false;
10830b57cec5SDimitry Andric     isCheap = true;
10840b57cec5SDimitry Andric   }
10850b57cec5SDimitry Andric 
10860b57cec5SDimitry Andric   return isCheap;
10870b57cec5SDimitry Andric }
10880b57cec5SDimitry Andric 
10890b57cec5SDimitry Andric /// Visit BBs from header to current BB, check if hoisting an instruction of the
10900b57cec5SDimitry Andric /// given cost matrix can cause high register pressure.
10910b57cec5SDimitry Andric bool
CanCauseHighRegPressure(const DenseMap<unsigned,int> & Cost,bool CheapInstr)10920b57cec5SDimitry Andric MachineLICMBase::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
10930b57cec5SDimitry Andric                                          bool CheapInstr) {
10940b57cec5SDimitry Andric   for (const auto &RPIdAndCost : Cost) {
10950b57cec5SDimitry Andric     if (RPIdAndCost.second <= 0)
10960b57cec5SDimitry Andric       continue;
10970b57cec5SDimitry Andric 
10980b57cec5SDimitry Andric     unsigned Class = RPIdAndCost.first;
10990b57cec5SDimitry Andric     int Limit = RegLimit[Class];
11000b57cec5SDimitry Andric 
11010b57cec5SDimitry Andric     // Don't hoist cheap instructions if they would increase register pressure,
11020b57cec5SDimitry Andric     // even if we're under the limit.
11030b57cec5SDimitry Andric     if (CheapInstr && !HoistCheapInsts)
11040b57cec5SDimitry Andric       return true;
11050b57cec5SDimitry Andric 
11060b57cec5SDimitry Andric     for (const auto &RP : BackTrace)
11070b57cec5SDimitry Andric       if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit)
11080b57cec5SDimitry Andric         return true;
11090b57cec5SDimitry Andric   }
11100b57cec5SDimitry Andric 
11110b57cec5SDimitry Andric   return false;
11120b57cec5SDimitry Andric }
11130b57cec5SDimitry Andric 
11140b57cec5SDimitry Andric /// Traverse the back trace from header to the current block and update their
11150b57cec5SDimitry Andric /// register pressures to reflect the effect of hoisting MI from the current
11160b57cec5SDimitry Andric /// block to the preheader.
UpdateBackTraceRegPressure(const MachineInstr * MI)11170b57cec5SDimitry Andric void MachineLICMBase::UpdateBackTraceRegPressure(const MachineInstr *MI) {
11180b57cec5SDimitry Andric   // First compute the 'cost' of the instruction, i.e. its contribution
11190b57cec5SDimitry Andric   // to register pressure.
11200b57cec5SDimitry Andric   auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
11210b57cec5SDimitry Andric                                /*ConsiderUnseenAsDef=*/false);
11220b57cec5SDimitry Andric 
11230b57cec5SDimitry Andric   // Update register pressure of blocks from loop header to current block.
11240b57cec5SDimitry Andric   for (auto &RP : BackTrace)
11250b57cec5SDimitry Andric     for (const auto &RPIdAndCost : Cost)
11260b57cec5SDimitry Andric       RP[RPIdAndCost.first] += RPIdAndCost.second;
11270b57cec5SDimitry Andric }
11280b57cec5SDimitry Andric 
11290b57cec5SDimitry Andric /// Return true if it is potentially profitable to hoist the given loop
11300b57cec5SDimitry Andric /// invariant.
IsProfitableToHoist(MachineInstr & MI)11310b57cec5SDimitry Andric bool MachineLICMBase::IsProfitableToHoist(MachineInstr &MI) {
11320b57cec5SDimitry Andric   if (MI.isImplicitDef())
11330b57cec5SDimitry Andric     return true;
11340b57cec5SDimitry Andric 
11350b57cec5SDimitry Andric   // Besides removing computation from the loop, hoisting an instruction has
11360b57cec5SDimitry Andric   // these effects:
11370b57cec5SDimitry Andric   //
11380b57cec5SDimitry Andric   // - The value defined by the instruction becomes live across the entire
11390b57cec5SDimitry Andric   //   loop. This increases register pressure in the loop.
11400b57cec5SDimitry Andric   //
11410b57cec5SDimitry Andric   // - If the value is used by a PHI in the loop, a copy will be required for
11420b57cec5SDimitry Andric   //   lowering the PHI after extending the live range.
11430b57cec5SDimitry Andric   //
11440b57cec5SDimitry Andric   // - When hoisting the last use of a value in the loop, that value no longer
11450b57cec5SDimitry Andric   //   needs to be live in the loop. This lowers register pressure in the loop.
11460b57cec5SDimitry Andric 
11470b57cec5SDimitry Andric   if (HoistConstStores &&  isCopyFeedingInvariantStore(MI, MRI, TRI))
11480b57cec5SDimitry Andric     return true;
11490b57cec5SDimitry Andric 
11500b57cec5SDimitry Andric   bool CheapInstr = IsCheapInstruction(MI);
11510b57cec5SDimitry Andric   bool CreatesCopy = HasLoopPHIUse(&MI);
11520b57cec5SDimitry Andric 
11530b57cec5SDimitry Andric   // Don't hoist a cheap instruction if it would create a copy in the loop.
11540b57cec5SDimitry Andric   if (CheapInstr && CreatesCopy) {
11550b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
11560b57cec5SDimitry Andric     return false;
11570b57cec5SDimitry Andric   }
11580b57cec5SDimitry Andric 
11590b57cec5SDimitry Andric   // Rematerializable instructions should always be hoisted since the register
11600b57cec5SDimitry Andric   // allocator can just pull them down again when needed.
11610b57cec5SDimitry Andric   if (TII->isTriviallyReMaterializable(MI, AA))
11620b57cec5SDimitry Andric     return true;
11630b57cec5SDimitry Andric 
11640b57cec5SDimitry Andric   // FIXME: If there are long latency loop-invariant instructions inside the
11650b57cec5SDimitry Andric   // loop at this point, why didn't the optimizer's LICM hoist them?
11660b57cec5SDimitry Andric   for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
11670b57cec5SDimitry Andric     const MachineOperand &MO = MI.getOperand(i);
11680b57cec5SDimitry Andric     if (!MO.isReg() || MO.isImplicit())
11690b57cec5SDimitry Andric       continue;
11708bcb0991SDimitry Andric     Register Reg = MO.getReg();
11718bcb0991SDimitry Andric     if (!Register::isVirtualRegister(Reg))
11720b57cec5SDimitry Andric       continue;
11730b57cec5SDimitry Andric     if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) {
11740b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Hoist High Latency: " << MI);
11750b57cec5SDimitry Andric       ++NumHighLatency;
11760b57cec5SDimitry Andric       return true;
11770b57cec5SDimitry Andric     }
11780b57cec5SDimitry Andric   }
11790b57cec5SDimitry Andric 
11800b57cec5SDimitry Andric   // Estimate register pressure to determine whether to LICM the instruction.
11810b57cec5SDimitry Andric   // In low register pressure situation, we can be more aggressive about
11820b57cec5SDimitry Andric   // hoisting. Also, favors hoisting long latency instructions even in
11830b57cec5SDimitry Andric   // moderately high pressure situation.
11840b57cec5SDimitry Andric   // Cheap instructions will only be hoisted if they don't increase register
11850b57cec5SDimitry Andric   // pressure at all.
11860b57cec5SDimitry Andric   auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
11870b57cec5SDimitry Andric                                /*ConsiderUnseenAsDef=*/false);
11880b57cec5SDimitry Andric 
11890b57cec5SDimitry Andric   // Visit BBs from header to current BB, if hoisting this doesn't cause
11900b57cec5SDimitry Andric   // high register pressure, then it's safe to proceed.
11910b57cec5SDimitry Andric   if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
11920b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
11930b57cec5SDimitry Andric     ++NumLowRP;
11940b57cec5SDimitry Andric     return true;
11950b57cec5SDimitry Andric   }
11960b57cec5SDimitry Andric 
11970b57cec5SDimitry Andric   // Don't risk increasing register pressure if it would create copies.
11980b57cec5SDimitry Andric   if (CreatesCopy) {
11990b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
12000b57cec5SDimitry Andric     return false;
12010b57cec5SDimitry Andric   }
12020b57cec5SDimitry Andric 
12030b57cec5SDimitry Andric   // Do not "speculate" in high register pressure situation. If an
12040b57cec5SDimitry Andric   // instruction is not guaranteed to be executed in the loop, it's best to be
12050b57cec5SDimitry Andric   // conservative.
12060b57cec5SDimitry Andric   if (AvoidSpeculation &&
12070b57cec5SDimitry Andric       (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
12080b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Won't speculate: " << MI);
12090b57cec5SDimitry Andric     return false;
12100b57cec5SDimitry Andric   }
12110b57cec5SDimitry Andric 
12120b57cec5SDimitry Andric   // High register pressure situation, only hoist if the instruction is going
12130b57cec5SDimitry Andric   // to be remat'ed.
12140b57cec5SDimitry Andric   if (!TII->isTriviallyReMaterializable(MI, AA) &&
12150b57cec5SDimitry Andric       !MI.isDereferenceableInvariantLoad(AA)) {
12160b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
12170b57cec5SDimitry Andric     return false;
12180b57cec5SDimitry Andric   }
12190b57cec5SDimitry Andric 
12200b57cec5SDimitry Andric   return true;
12210b57cec5SDimitry Andric }
12220b57cec5SDimitry Andric 
12230b57cec5SDimitry Andric /// Unfold a load from the given machineinstr if the load itself could be
12240b57cec5SDimitry Andric /// hoisted. Return the unfolded and hoistable load, or null if the load
12250b57cec5SDimitry Andric /// couldn't be unfolded or if it wouldn't be hoistable.
ExtractHoistableLoad(MachineInstr * MI)12260b57cec5SDimitry Andric MachineInstr *MachineLICMBase::ExtractHoistableLoad(MachineInstr *MI) {
12270b57cec5SDimitry Andric   // Don't unfold simple loads.
12280b57cec5SDimitry Andric   if (MI->canFoldAsLoad())
12290b57cec5SDimitry Andric     return nullptr;
12300b57cec5SDimitry Andric 
12310b57cec5SDimitry Andric   // If not, we may be able to unfold a load and hoist that.
12320b57cec5SDimitry Andric   // First test whether the instruction is loading from an amenable
12330b57cec5SDimitry Andric   // memory location.
12340b57cec5SDimitry Andric   if (!MI->isDereferenceableInvariantLoad(AA))
12350b57cec5SDimitry Andric     return nullptr;
12360b57cec5SDimitry Andric 
12370b57cec5SDimitry Andric   // Next determine the register class for a temporary register.
12380b57cec5SDimitry Andric   unsigned LoadRegIndex;
12390b57cec5SDimitry Andric   unsigned NewOpc =
12400b57cec5SDimitry Andric     TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
12410b57cec5SDimitry Andric                                     /*UnfoldLoad=*/true,
12420b57cec5SDimitry Andric                                     /*UnfoldStore=*/false,
12430b57cec5SDimitry Andric                                     &LoadRegIndex);
12440b57cec5SDimitry Andric   if (NewOpc == 0) return nullptr;
12450b57cec5SDimitry Andric   const MCInstrDesc &MID = TII->get(NewOpc);
12460b57cec5SDimitry Andric   MachineFunction &MF = *MI->getMF();
12470b57cec5SDimitry Andric   const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
12480b57cec5SDimitry Andric   // Ok, we're unfolding. Create a temporary register and do the unfold.
12498bcb0991SDimitry Andric   Register Reg = MRI->createVirtualRegister(RC);
12500b57cec5SDimitry Andric 
12510b57cec5SDimitry Andric   SmallVector<MachineInstr *, 2> NewMIs;
12520b57cec5SDimitry Andric   bool Success = TII->unfoldMemoryOperand(MF, *MI, Reg,
12530b57cec5SDimitry Andric                                           /*UnfoldLoad=*/true,
12540b57cec5SDimitry Andric                                           /*UnfoldStore=*/false, NewMIs);
12550b57cec5SDimitry Andric   (void)Success;
12560b57cec5SDimitry Andric   assert(Success &&
12570b57cec5SDimitry Andric          "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
12580b57cec5SDimitry Andric          "succeeded!");
12590b57cec5SDimitry Andric   assert(NewMIs.size() == 2 &&
12600b57cec5SDimitry Andric          "Unfolded a load into multiple instructions!");
12610b57cec5SDimitry Andric   MachineBasicBlock *MBB = MI->getParent();
12620b57cec5SDimitry Andric   MachineBasicBlock::iterator Pos = MI;
12630b57cec5SDimitry Andric   MBB->insert(Pos, NewMIs[0]);
12640b57cec5SDimitry Andric   MBB->insert(Pos, NewMIs[1]);
12650b57cec5SDimitry Andric   // If unfolding produced a load that wasn't loop-invariant or profitable to
12660b57cec5SDimitry Andric   // hoist, discard the new instructions and bail.
12670b57cec5SDimitry Andric   if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
12680b57cec5SDimitry Andric     NewMIs[0]->eraseFromParent();
12690b57cec5SDimitry Andric     NewMIs[1]->eraseFromParent();
12700b57cec5SDimitry Andric     return nullptr;
12710b57cec5SDimitry Andric   }
12720b57cec5SDimitry Andric 
12730b57cec5SDimitry Andric   // Update register pressure for the unfolded instruction.
12740b57cec5SDimitry Andric   UpdateRegPressure(NewMIs[1]);
12750b57cec5SDimitry Andric 
12760b57cec5SDimitry Andric   // Otherwise we successfully unfolded a load that we can hoist.
12775ffd83dbSDimitry Andric 
12785ffd83dbSDimitry Andric   // Update the call site info.
12795ffd83dbSDimitry Andric   if (MI->shouldUpdateCallSiteInfo())
12805ffd83dbSDimitry Andric     MF.eraseCallSiteInfo(MI);
12815ffd83dbSDimitry Andric 
12820b57cec5SDimitry Andric   MI->eraseFromParent();
12830b57cec5SDimitry Andric   return NewMIs[0];
12840b57cec5SDimitry Andric }
12850b57cec5SDimitry Andric 
12860b57cec5SDimitry Andric /// Initialize the CSE map with instructions that are in the current loop
12870b57cec5SDimitry Andric /// preheader that may become duplicates of instructions that are hoisted
12880b57cec5SDimitry Andric /// out of the loop.
InitCSEMap(MachineBasicBlock * BB)12890b57cec5SDimitry Andric void MachineLICMBase::InitCSEMap(MachineBasicBlock *BB) {
12900b57cec5SDimitry Andric   for (MachineInstr &MI : *BB)
12910b57cec5SDimitry Andric     CSEMap[MI.getOpcode()].push_back(&MI);
12920b57cec5SDimitry Andric }
12930b57cec5SDimitry Andric 
12940b57cec5SDimitry Andric /// Find an instruction amount PrevMIs that is a duplicate of MI.
12950b57cec5SDimitry Andric /// Return this instruction if it's found.
1296af732203SDimitry Andric MachineInstr *
LookForDuplicate(const MachineInstr * MI,std::vector<MachineInstr * > & PrevMIs)12970b57cec5SDimitry Andric MachineLICMBase::LookForDuplicate(const MachineInstr *MI,
1298af732203SDimitry Andric                                   std::vector<MachineInstr *> &PrevMIs) {
1299af732203SDimitry Andric   for (MachineInstr *PrevMI : PrevMIs)
13000b57cec5SDimitry Andric     if (TII->produceSameValue(*MI, *PrevMI, (PreRegAlloc ? MRI : nullptr)))
13010b57cec5SDimitry Andric       return PrevMI;
13020b57cec5SDimitry Andric 
13030b57cec5SDimitry Andric   return nullptr;
13040b57cec5SDimitry Andric }
13050b57cec5SDimitry Andric 
13060b57cec5SDimitry Andric /// Given a LICM'ed instruction, look for an instruction on the preheader that
13070b57cec5SDimitry Andric /// computes the same value. If it's found, do a RAU on with the definition of
13080b57cec5SDimitry Andric /// the existing instruction rather than hoisting the instruction to the
13090b57cec5SDimitry Andric /// preheader.
EliminateCSE(MachineInstr * MI,DenseMap<unsigned,std::vector<MachineInstr * >>::iterator & CI)1310af732203SDimitry Andric bool MachineLICMBase::EliminateCSE(
1311af732203SDimitry Andric     MachineInstr *MI,
1312af732203SDimitry Andric     DenseMap<unsigned, std::vector<MachineInstr *>>::iterator &CI) {
13130b57cec5SDimitry Andric   // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
13140b57cec5SDimitry Andric   // the undef property onto uses.
13150b57cec5SDimitry Andric   if (CI == CSEMap.end() || MI->isImplicitDef())
13160b57cec5SDimitry Andric     return false;
13170b57cec5SDimitry Andric 
1318af732203SDimitry Andric   if (MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
13190b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
13200b57cec5SDimitry Andric 
13210b57cec5SDimitry Andric     // Replace virtual registers defined by MI by their counterparts defined
13220b57cec5SDimitry Andric     // by Dup.
13230b57cec5SDimitry Andric     SmallVector<unsigned, 2> Defs;
13240b57cec5SDimitry Andric     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
13250b57cec5SDimitry Andric       const MachineOperand &MO = MI->getOperand(i);
13260b57cec5SDimitry Andric 
13270b57cec5SDimitry Andric       // Physical registers may not differ here.
13280b57cec5SDimitry Andric       assert((!MO.isReg() || MO.getReg() == 0 ||
13298bcb0991SDimitry Andric               !Register::isPhysicalRegister(MO.getReg()) ||
13300b57cec5SDimitry Andric               MO.getReg() == Dup->getOperand(i).getReg()) &&
13310b57cec5SDimitry Andric              "Instructions with different phys regs are not identical!");
13320b57cec5SDimitry Andric 
13330b57cec5SDimitry Andric       if (MO.isReg() && MO.isDef() &&
13348bcb0991SDimitry Andric           !Register::isPhysicalRegister(MO.getReg()))
13350b57cec5SDimitry Andric         Defs.push_back(i);
13360b57cec5SDimitry Andric     }
13370b57cec5SDimitry Andric 
13380b57cec5SDimitry Andric     SmallVector<const TargetRegisterClass*, 2> OrigRCs;
13390b57cec5SDimitry Andric     for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
13400b57cec5SDimitry Andric       unsigned Idx = Defs[i];
13418bcb0991SDimitry Andric       Register Reg = MI->getOperand(Idx).getReg();
13428bcb0991SDimitry Andric       Register DupReg = Dup->getOperand(Idx).getReg();
13430b57cec5SDimitry Andric       OrigRCs.push_back(MRI->getRegClass(DupReg));
13440b57cec5SDimitry Andric 
13450b57cec5SDimitry Andric       if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
13460b57cec5SDimitry Andric         // Restore old RCs if more than one defs.
13470b57cec5SDimitry Andric         for (unsigned j = 0; j != i; ++j)
13480b57cec5SDimitry Andric           MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
13490b57cec5SDimitry Andric         return false;
13500b57cec5SDimitry Andric       }
13510b57cec5SDimitry Andric     }
13520b57cec5SDimitry Andric 
13530b57cec5SDimitry Andric     for (unsigned Idx : Defs) {
13548bcb0991SDimitry Andric       Register Reg = MI->getOperand(Idx).getReg();
13558bcb0991SDimitry Andric       Register DupReg = Dup->getOperand(Idx).getReg();
13560b57cec5SDimitry Andric       MRI->replaceRegWith(Reg, DupReg);
13570b57cec5SDimitry Andric       MRI->clearKillFlags(DupReg);
1358af732203SDimitry Andric       // Clear Dup dead flag if any, we reuse it for Reg.
1359af732203SDimitry Andric       if (!MRI->use_nodbg_empty(DupReg))
1360af732203SDimitry Andric         Dup->getOperand(Idx).setIsDead(false);
13610b57cec5SDimitry Andric     }
13620b57cec5SDimitry Andric 
13630b57cec5SDimitry Andric     MI->eraseFromParent();
13640b57cec5SDimitry Andric     ++NumCSEed;
13650b57cec5SDimitry Andric     return true;
13660b57cec5SDimitry Andric   }
13670b57cec5SDimitry Andric   return false;
13680b57cec5SDimitry Andric }
13690b57cec5SDimitry Andric 
13700b57cec5SDimitry Andric /// Return true if the given instruction will be CSE'd if it's hoisted out of
13710b57cec5SDimitry Andric /// the loop.
MayCSE(MachineInstr * MI)13720b57cec5SDimitry Andric bool MachineLICMBase::MayCSE(MachineInstr *MI) {
13730b57cec5SDimitry Andric   unsigned Opcode = MI->getOpcode();
1374af732203SDimitry Andric   DenseMap<unsigned, std::vector<MachineInstr *>>::iterator CI =
1375af732203SDimitry Andric       CSEMap.find(Opcode);
13760b57cec5SDimitry Andric   // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
13770b57cec5SDimitry Andric   // the undef property onto uses.
13780b57cec5SDimitry Andric   if (CI == CSEMap.end() || MI->isImplicitDef())
13790b57cec5SDimitry Andric     return false;
13800b57cec5SDimitry Andric 
13810b57cec5SDimitry Andric   return LookForDuplicate(MI, CI->second) != nullptr;
13820b57cec5SDimitry Andric }
13830b57cec5SDimitry Andric 
13840b57cec5SDimitry Andric /// When an instruction is found to use only loop invariant operands
13850b57cec5SDimitry Andric /// that are safe to hoist, this instruction is called to do the dirty work.
13860b57cec5SDimitry Andric /// It returns true if the instruction is hoisted.
Hoist(MachineInstr * MI,MachineBasicBlock * Preheader)13870b57cec5SDimitry Andric bool MachineLICMBase::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
1388480093f4SDimitry Andric   MachineBasicBlock *SrcBlock = MI->getParent();
1389480093f4SDimitry Andric 
1390480093f4SDimitry Andric   // Disable the instruction hoisting due to block hotness
1391480093f4SDimitry Andric   if ((DisableHoistingToHotterBlocks == UseBFI::All ||
1392480093f4SDimitry Andric       (DisableHoistingToHotterBlocks == UseBFI::PGO && HasProfileData)) &&
1393480093f4SDimitry Andric       isTgtHotterThanSrc(SrcBlock, Preheader)) {
1394480093f4SDimitry Andric     ++NumNotHoistedDueToHotness;
1395480093f4SDimitry Andric     return false;
1396480093f4SDimitry Andric   }
13970b57cec5SDimitry Andric   // First check whether we should hoist this instruction.
13980b57cec5SDimitry Andric   if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
13990b57cec5SDimitry Andric     // If not, try unfolding a hoistable load.
14000b57cec5SDimitry Andric     MI = ExtractHoistableLoad(MI);
14010b57cec5SDimitry Andric     if (!MI) return false;
14020b57cec5SDimitry Andric   }
14030b57cec5SDimitry Andric 
14040b57cec5SDimitry Andric   // If we have hoisted an instruction that may store, it can only be a constant
14050b57cec5SDimitry Andric   // store.
14060b57cec5SDimitry Andric   if (MI->mayStore())
14070b57cec5SDimitry Andric     NumStoreConst++;
14080b57cec5SDimitry Andric 
14090b57cec5SDimitry Andric   // Now move the instructions to the predecessor, inserting it before any
14100b57cec5SDimitry Andric   // terminator instructions.
14110b57cec5SDimitry Andric   LLVM_DEBUG({
14120b57cec5SDimitry Andric     dbgs() << "Hoisting " << *MI;
14130b57cec5SDimitry Andric     if (MI->getParent()->getBasicBlock())
14140b57cec5SDimitry Andric       dbgs() << " from " << printMBBReference(*MI->getParent());
14150b57cec5SDimitry Andric     if (Preheader->getBasicBlock())
14160b57cec5SDimitry Andric       dbgs() << " to " << printMBBReference(*Preheader);
14170b57cec5SDimitry Andric     dbgs() << "\n";
14180b57cec5SDimitry Andric   });
14190b57cec5SDimitry Andric 
14200b57cec5SDimitry Andric   // If this is the first instruction being hoisted to the preheader,
14210b57cec5SDimitry Andric   // initialize the CSE map with potential common expressions.
14220b57cec5SDimitry Andric   if (FirstInLoop) {
14230b57cec5SDimitry Andric     InitCSEMap(Preheader);
14240b57cec5SDimitry Andric     FirstInLoop = false;
14250b57cec5SDimitry Andric   }
14260b57cec5SDimitry Andric 
14270b57cec5SDimitry Andric   // Look for opportunity to CSE the hoisted instruction.
14280b57cec5SDimitry Andric   unsigned Opcode = MI->getOpcode();
1429af732203SDimitry Andric   DenseMap<unsigned, std::vector<MachineInstr *>>::iterator CI =
1430af732203SDimitry Andric       CSEMap.find(Opcode);
14310b57cec5SDimitry Andric   if (!EliminateCSE(MI, CI)) {
14320b57cec5SDimitry Andric     // Otherwise, splice the instruction to the preheader.
14330b57cec5SDimitry Andric     Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
14340b57cec5SDimitry Andric 
14350b57cec5SDimitry Andric     // Since we are moving the instruction out of its basic block, we do not
14360b57cec5SDimitry Andric     // retain its debug location. Doing so would degrade the debugging
14370b57cec5SDimitry Andric     // experience and adversely affect the accuracy of profiling information.
14385ffd83dbSDimitry Andric     assert(!MI->isDebugInstr() && "Should not hoist debug inst");
14390b57cec5SDimitry Andric     MI->setDebugLoc(DebugLoc());
14400b57cec5SDimitry Andric 
14410b57cec5SDimitry Andric     // Update register pressure for BBs from header to this block.
14420b57cec5SDimitry Andric     UpdateBackTraceRegPressure(MI);
14430b57cec5SDimitry Andric 
14440b57cec5SDimitry Andric     // Clear the kill flags of any register this instruction defines,
14450b57cec5SDimitry Andric     // since they may need to be live throughout the entire loop
14460b57cec5SDimitry Andric     // rather than just live for part of it.
14470b57cec5SDimitry Andric     for (MachineOperand &MO : MI->operands())
14480b57cec5SDimitry Andric       if (MO.isReg() && MO.isDef() && !MO.isDead())
14490b57cec5SDimitry Andric         MRI->clearKillFlags(MO.getReg());
14500b57cec5SDimitry Andric 
14510b57cec5SDimitry Andric     // Add to the CSE map.
14520b57cec5SDimitry Andric     if (CI != CSEMap.end())
14530b57cec5SDimitry Andric       CI->second.push_back(MI);
14540b57cec5SDimitry Andric     else
14550b57cec5SDimitry Andric       CSEMap[Opcode].push_back(MI);
14560b57cec5SDimitry Andric   }
14570b57cec5SDimitry Andric 
14580b57cec5SDimitry Andric   ++NumHoisted;
14590b57cec5SDimitry Andric   Changed = true;
14600b57cec5SDimitry Andric 
14610b57cec5SDimitry Andric   return true;
14620b57cec5SDimitry Andric }
14630b57cec5SDimitry Andric 
14640b57cec5SDimitry Andric /// Get the preheader for the current loop, splitting a critical edge if needed.
getCurPreheader()14650b57cec5SDimitry Andric MachineBasicBlock *MachineLICMBase::getCurPreheader() {
14660b57cec5SDimitry Andric   // Determine the block to which to hoist instructions. If we can't find a
14670b57cec5SDimitry Andric   // suitable loop predecessor, we can't do any hoisting.
14680b57cec5SDimitry Andric 
14690b57cec5SDimitry Andric   // If we've tried to get a preheader and failed, don't try again.
14700b57cec5SDimitry Andric   if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
14710b57cec5SDimitry Andric     return nullptr;
14720b57cec5SDimitry Andric 
14730b57cec5SDimitry Andric   if (!CurPreheader) {
14740b57cec5SDimitry Andric     CurPreheader = CurLoop->getLoopPreheader();
14750b57cec5SDimitry Andric     if (!CurPreheader) {
14760b57cec5SDimitry Andric       MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
14770b57cec5SDimitry Andric       if (!Pred) {
14780b57cec5SDimitry Andric         CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
14790b57cec5SDimitry Andric         return nullptr;
14800b57cec5SDimitry Andric       }
14810b57cec5SDimitry Andric 
14820b57cec5SDimitry Andric       CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), *this);
14830b57cec5SDimitry Andric       if (!CurPreheader) {
14840b57cec5SDimitry Andric         CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
14850b57cec5SDimitry Andric         return nullptr;
14860b57cec5SDimitry Andric       }
14870b57cec5SDimitry Andric     }
14880b57cec5SDimitry Andric   }
14890b57cec5SDimitry Andric   return CurPreheader;
14900b57cec5SDimitry Andric }
1491480093f4SDimitry Andric 
1492480093f4SDimitry Andric /// Is the target basic block at least "BlockFrequencyRatioThreshold"
1493480093f4SDimitry Andric /// times hotter than the source basic block.
isTgtHotterThanSrc(MachineBasicBlock * SrcBlock,MachineBasicBlock * TgtBlock)1494480093f4SDimitry Andric bool MachineLICMBase::isTgtHotterThanSrc(MachineBasicBlock *SrcBlock,
1495480093f4SDimitry Andric                                          MachineBasicBlock *TgtBlock) {
1496480093f4SDimitry Andric   // Parse source and target basic block frequency from MBFI
1497480093f4SDimitry Andric   uint64_t SrcBF = MBFI->getBlockFreq(SrcBlock).getFrequency();
1498480093f4SDimitry Andric   uint64_t DstBF = MBFI->getBlockFreq(TgtBlock).getFrequency();
1499480093f4SDimitry Andric 
1500480093f4SDimitry Andric   // Disable the hoisting if source block frequency is zero
1501480093f4SDimitry Andric   if (!SrcBF)
1502480093f4SDimitry Andric     return true;
1503480093f4SDimitry Andric 
1504480093f4SDimitry Andric   double Ratio = (double)DstBF / SrcBF;
1505480093f4SDimitry Andric 
1506480093f4SDimitry Andric   // Compare the block frequency ratio with the threshold
1507480093f4SDimitry Andric   return Ratio > BlockFrequencyRatioThreshold;
1508480093f4SDimitry Andric }
1509