xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/MachineLICM.cpp (revision 9e5787d2284e187abb5b654d924394a65772e004)
1 //===- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass performs loop invariant code motion on machine instructions. We
10 // attempt to remove as much code from the body of a loop as possible.
11 //
12 // This pass is not intended to be a replacement or a complete alternative
13 // for the LLVM-IR-level LICM pass. It is only designed to hoist simple
14 // constructs that are not exposed before lowering and instruction selection.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineBasicBlock.h"
26 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
27 #include "llvm/CodeGen/MachineDominators.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineFunctionPass.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/CodeGen/MachineLoopInfo.h"
33 #include "llvm/CodeGen/MachineMemOperand.h"
34 #include "llvm/CodeGen/MachineOperand.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/CodeGen/TargetInstrInfo.h"
38 #include "llvm/CodeGen/TargetLowering.h"
39 #include "llvm/CodeGen/TargetRegisterInfo.h"
40 #include "llvm/CodeGen/TargetSchedule.h"
41 #include "llvm/CodeGen/TargetSubtargetInfo.h"
42 #include "llvm/IR/DebugLoc.h"
43 #include "llvm/InitializePasses.h"
44 #include "llvm/MC/MCInstrDesc.h"
45 #include "llvm/MC/MCRegisterInfo.h"
46 #include "llvm/Pass.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include <algorithm>
52 #include <cassert>
53 #include <limits>
54 #include <vector>
55 
56 using namespace llvm;
57 
58 #define DEBUG_TYPE "machinelicm"
59 
60 static cl::opt<bool>
61 AvoidSpeculation("avoid-speculation",
62                  cl::desc("MachineLICM should avoid speculation"),
63                  cl::init(true), cl::Hidden);
64 
65 static cl::opt<bool>
66 HoistCheapInsts("hoist-cheap-insts",
67                 cl::desc("MachineLICM should hoist even cheap instructions"),
68                 cl::init(false), cl::Hidden);
69 
70 static cl::opt<bool>
71 SinkInstsToAvoidSpills("sink-insts-to-avoid-spills",
72                        cl::desc("MachineLICM should sink instructions into "
73                                 "loops to avoid register spills"),
74                        cl::init(false), cl::Hidden);
75 static cl::opt<bool>
76 HoistConstStores("hoist-const-stores",
77                  cl::desc("Hoist invariant stores"),
78                  cl::init(true), cl::Hidden);
79 // The default threshold of 100 (i.e. if target block is 100 times hotter)
80 // is based on empirical data on a single target and is subject to tuning.
81 static cl::opt<unsigned>
82 BlockFrequencyRatioThreshold("block-freq-ratio-threshold",
83                              cl::desc("Do not hoist instructions if target"
84                              "block is N times hotter than the source."),
85                              cl::init(100), cl::Hidden);
86 
87 enum class UseBFI { None, PGO, All };
88 
89 static cl::opt<UseBFI>
90 DisableHoistingToHotterBlocks("disable-hoisting-to-hotter-blocks",
91                               cl::desc("Disable hoisting instructions to"
92                               " hotter blocks"),
93                               cl::init(UseBFI::None), cl::Hidden,
94                               cl::values(clEnumValN(UseBFI::None, "none",
95                               "disable the feature"),
96                               clEnumValN(UseBFI::PGO, "pgo",
97                               "enable the feature when using profile data"),
98                               clEnumValN(UseBFI::All, "all",
99                               "enable the feature with/wo profile data")));
100 
101 STATISTIC(NumHoisted,
102           "Number of machine instructions hoisted out of loops");
103 STATISTIC(NumLowRP,
104           "Number of instructions hoisted in low reg pressure situation");
105 STATISTIC(NumHighLatency,
106           "Number of high latency instructions hoisted");
107 STATISTIC(NumCSEed,
108           "Number of hoisted machine instructions CSEed");
109 STATISTIC(NumPostRAHoisted,
110           "Number of machine instructions hoisted out of loops post regalloc");
111 STATISTIC(NumStoreConst,
112           "Number of stores of const phys reg hoisted out of loops");
113 STATISTIC(NumNotHoistedDueToHotness,
114           "Number of instructions not hoisted due to block frequency");
115 
116 namespace {
117 
118   class MachineLICMBase : public MachineFunctionPass {
119     const TargetInstrInfo *TII;
120     const TargetLoweringBase *TLI;
121     const TargetRegisterInfo *TRI;
122     const MachineFrameInfo *MFI;
123     MachineRegisterInfo *MRI;
124     TargetSchedModel SchedModel;
125     bool PreRegAlloc;
126     bool HasProfileData;
127 
128     // Various analyses that we use...
129     AliasAnalysis        *AA;      // Alias analysis info.
130     MachineBlockFrequencyInfo *MBFI; // Machine block frequncy info
131     MachineLoopInfo      *MLI;     // Current MachineLoopInfo
132     MachineDominatorTree *DT;      // Machine dominator tree for the cur loop
133 
134     // State that is updated as we process loops
135     bool         Changed;          // True if a loop is changed.
136     bool         FirstInLoop;      // True if it's the first LICM in the loop.
137     MachineLoop *CurLoop;          // The current loop we are working on.
138     MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
139 
140     // Exit blocks for CurLoop.
141     SmallVector<MachineBasicBlock *, 8> ExitBlocks;
142 
143     bool isExitBlock(const MachineBasicBlock *MBB) const {
144       return is_contained(ExitBlocks, MBB);
145     }
146 
147     // Track 'estimated' register pressure.
148     SmallSet<unsigned, 32> RegSeen;
149     SmallVector<unsigned, 8> RegPressure;
150 
151     // Register pressure "limit" per register pressure set. If the pressure
152     // is higher than the limit, then it's considered high.
153     SmallVector<unsigned, 8> RegLimit;
154 
155     // Register pressure on path leading from loop preheader to current BB.
156     SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
157 
158     // For each opcode, keep a list of potential CSE instructions.
159     DenseMap<unsigned, std::vector<const MachineInstr *>> CSEMap;
160 
161     enum {
162       SpeculateFalse   = 0,
163       SpeculateTrue    = 1,
164       SpeculateUnknown = 2
165     };
166 
167     // If a MBB does not dominate loop exiting blocks then it may not safe
168     // to hoist loads from this block.
169     // Tri-state: 0 - false, 1 - true, 2 - unknown
170     unsigned SpeculationState;
171 
172   public:
173     MachineLICMBase(char &PassID, bool PreRegAlloc)
174         : MachineFunctionPass(PassID), PreRegAlloc(PreRegAlloc) {}
175 
176     bool runOnMachineFunction(MachineFunction &MF) override;
177 
178     void getAnalysisUsage(AnalysisUsage &AU) const override {
179       AU.addRequired<MachineLoopInfo>();
180       if (DisableHoistingToHotterBlocks != UseBFI::None)
181         AU.addRequired<MachineBlockFrequencyInfo>();
182       AU.addRequired<MachineDominatorTree>();
183       AU.addRequired<AAResultsWrapperPass>();
184       AU.addPreserved<MachineLoopInfo>();
185       MachineFunctionPass::getAnalysisUsage(AU);
186     }
187 
188     void releaseMemory() override {
189       RegSeen.clear();
190       RegPressure.clear();
191       RegLimit.clear();
192       BackTrace.clear();
193       CSEMap.clear();
194     }
195 
196   private:
197     /// Keep track of information about hoisting candidates.
198     struct CandidateInfo {
199       MachineInstr *MI;
200       unsigned      Def;
201       int           FI;
202 
203       CandidateInfo(MachineInstr *mi, unsigned def, int fi)
204         : MI(mi), Def(def), FI(fi) {}
205     };
206 
207     void HoistRegionPostRA();
208 
209     void HoistPostRA(MachineInstr *MI, unsigned Def);
210 
211     void ProcessMI(MachineInstr *MI, BitVector &PhysRegDefs,
212                    BitVector &PhysRegClobbers, SmallSet<int, 32> &StoredFIs,
213                    SmallVectorImpl<CandidateInfo> &Candidates);
214 
215     void AddToLiveIns(unsigned Reg);
216 
217     bool IsLICMCandidate(MachineInstr &I);
218 
219     bool IsLoopInvariantInst(MachineInstr &I);
220 
221     bool HasLoopPHIUse(const MachineInstr *MI) const;
222 
223     bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
224                                unsigned Reg) const;
225 
226     bool IsCheapInstruction(MachineInstr &MI) const;
227 
228     bool CanCauseHighRegPressure(const DenseMap<unsigned, int> &Cost,
229                                  bool Cheap);
230 
231     void UpdateBackTraceRegPressure(const MachineInstr *MI);
232 
233     bool IsProfitableToHoist(MachineInstr &MI);
234 
235     bool IsGuaranteedToExecute(MachineBasicBlock *BB);
236 
237     void EnterScope(MachineBasicBlock *MBB);
238 
239     void ExitScope(MachineBasicBlock *MBB);
240 
241     void ExitScopeIfDone(
242         MachineDomTreeNode *Node,
243         DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren,
244         DenseMap<MachineDomTreeNode *, MachineDomTreeNode *> &ParentMap);
245 
246     void HoistOutOfLoop(MachineDomTreeNode *HeaderN);
247 
248     void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
249 
250     void SinkIntoLoop();
251 
252     void InitRegPressure(MachineBasicBlock *BB);
253 
254     DenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI,
255                                              bool ConsiderSeen,
256                                              bool ConsiderUnseenAsDef);
257 
258     void UpdateRegPressure(const MachineInstr *MI,
259                            bool ConsiderUnseenAsDef = false);
260 
261     MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
262 
263     const MachineInstr *
264     LookForDuplicate(const MachineInstr *MI,
265                      std::vector<const MachineInstr *> &PrevMIs);
266 
267     bool EliminateCSE(
268         MachineInstr *MI,
269         DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI);
270 
271     bool MayCSE(MachineInstr *MI);
272 
273     bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
274 
275     void InitCSEMap(MachineBasicBlock *BB);
276 
277     bool isTgtHotterThanSrc(MachineBasicBlock *SrcBlock,
278                             MachineBasicBlock *TgtBlock);
279     MachineBasicBlock *getCurPreheader();
280   };
281 
282   class MachineLICM : public MachineLICMBase {
283   public:
284     static char ID;
285     MachineLICM() : MachineLICMBase(ID, false) {
286       initializeMachineLICMPass(*PassRegistry::getPassRegistry());
287     }
288   };
289 
290   class EarlyMachineLICM : public MachineLICMBase {
291   public:
292     static char ID;
293     EarlyMachineLICM() : MachineLICMBase(ID, true) {
294       initializeEarlyMachineLICMPass(*PassRegistry::getPassRegistry());
295     }
296   };
297 
298 } // end anonymous namespace
299 
300 char MachineLICM::ID;
301 char EarlyMachineLICM::ID;
302 
303 char &llvm::MachineLICMID = MachineLICM::ID;
304 char &llvm::EarlyMachineLICMID = EarlyMachineLICM::ID;
305 
306 INITIALIZE_PASS_BEGIN(MachineLICM, DEBUG_TYPE,
307                       "Machine Loop Invariant Code Motion", false, false)
308 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
309 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
310 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
311 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
312 INITIALIZE_PASS_END(MachineLICM, DEBUG_TYPE,
313                     "Machine Loop Invariant Code Motion", false, false)
314 
315 INITIALIZE_PASS_BEGIN(EarlyMachineLICM, "early-machinelicm",
316                       "Early Machine Loop Invariant Code Motion", false, false)
317 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
318 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
319 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
320 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
321 INITIALIZE_PASS_END(EarlyMachineLICM, "early-machinelicm",
322                     "Early Machine Loop Invariant Code Motion", false, false)
323 
324 /// Test if the given loop is the outer-most loop that has a unique predecessor.
325 static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
326   // Check whether this loop even has a unique predecessor.
327   if (!CurLoop->getLoopPredecessor())
328     return false;
329   // Ok, now check to see if any of its outer loops do.
330   for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
331     if (L->getLoopPredecessor())
332       return false;
333   // None of them did, so this is the outermost with a unique predecessor.
334   return true;
335 }
336 
337 bool MachineLICMBase::runOnMachineFunction(MachineFunction &MF) {
338   if (skipFunction(MF.getFunction()))
339     return false;
340 
341   Changed = FirstInLoop = false;
342   const TargetSubtargetInfo &ST = MF.getSubtarget();
343   TII = ST.getInstrInfo();
344   TLI = ST.getTargetLowering();
345   TRI = ST.getRegisterInfo();
346   MFI = &MF.getFrameInfo();
347   MRI = &MF.getRegInfo();
348   SchedModel.init(&ST);
349 
350   PreRegAlloc = MRI->isSSA();
351   HasProfileData = MF.getFunction().hasProfileData();
352 
353   if (PreRegAlloc)
354     LLVM_DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
355   else
356     LLVM_DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
357   LLVM_DEBUG(dbgs() << MF.getName() << " ********\n");
358 
359   if (PreRegAlloc) {
360     // Estimate register pressure during pre-regalloc pass.
361     unsigned NumRPS = TRI->getNumRegPressureSets();
362     RegPressure.resize(NumRPS);
363     std::fill(RegPressure.begin(), RegPressure.end(), 0);
364     RegLimit.resize(NumRPS);
365     for (unsigned i = 0, e = NumRPS; i != e; ++i)
366       RegLimit[i] = TRI->getRegPressureSetLimit(MF, i);
367   }
368 
369   // Get our Loop information...
370   if (DisableHoistingToHotterBlocks != UseBFI::None)
371     MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
372   MLI = &getAnalysis<MachineLoopInfo>();
373   DT  = &getAnalysis<MachineDominatorTree>();
374   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
375 
376   SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
377   while (!Worklist.empty()) {
378     CurLoop = Worklist.pop_back_val();
379     CurPreheader = nullptr;
380     ExitBlocks.clear();
381 
382     // If this is done before regalloc, only visit outer-most preheader-sporting
383     // loops.
384     if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
385       Worklist.append(CurLoop->begin(), CurLoop->end());
386       continue;
387     }
388 
389     CurLoop->getExitBlocks(ExitBlocks);
390 
391     if (!PreRegAlloc)
392       HoistRegionPostRA();
393     else {
394       // CSEMap is initialized for loop header when the first instruction is
395       // being hoisted.
396       MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
397       FirstInLoop = true;
398       HoistOutOfLoop(N);
399       CSEMap.clear();
400 
401       if (SinkInstsToAvoidSpills)
402         SinkIntoLoop();
403     }
404   }
405 
406   return Changed;
407 }
408 
409 /// Return true if instruction stores to the specified frame.
410 static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
411   // Check mayStore before memory operands so that e.g. DBG_VALUEs will return
412   // true since they have no memory operands.
413   if (!MI->mayStore())
414      return false;
415   // If we lost memory operands, conservatively assume that the instruction
416   // writes to all slots.
417   if (MI->memoperands_empty())
418     return true;
419   for (const MachineMemOperand *MemOp : MI->memoperands()) {
420     if (!MemOp->isStore() || !MemOp->getPseudoValue())
421       continue;
422     if (const FixedStackPseudoSourceValue *Value =
423         dyn_cast<FixedStackPseudoSourceValue>(MemOp->getPseudoValue())) {
424       if (Value->getFrameIndex() == FI)
425         return true;
426     }
427   }
428   return false;
429 }
430 
431 /// Examine the instruction for potentai LICM candidate. Also
432 /// gather register def and frame object update information.
433 void MachineLICMBase::ProcessMI(MachineInstr *MI,
434                                 BitVector &PhysRegDefs,
435                                 BitVector &PhysRegClobbers,
436                                 SmallSet<int, 32> &StoredFIs,
437                                 SmallVectorImpl<CandidateInfo> &Candidates) {
438   bool RuledOut = false;
439   bool HasNonInvariantUse = false;
440   unsigned Def = 0;
441   for (const MachineOperand &MO : MI->operands()) {
442     if (MO.isFI()) {
443       // Remember if the instruction stores to the frame index.
444       int FI = MO.getIndex();
445       if (!StoredFIs.count(FI) &&
446           MFI->isSpillSlotObjectIndex(FI) &&
447           InstructionStoresToFI(MI, FI))
448         StoredFIs.insert(FI);
449       HasNonInvariantUse = true;
450       continue;
451     }
452 
453     // We can't hoist an instruction defining a physreg that is clobbered in
454     // the loop.
455     if (MO.isRegMask()) {
456       PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
457       continue;
458     }
459 
460     if (!MO.isReg())
461       continue;
462     Register Reg = MO.getReg();
463     if (!Reg)
464       continue;
465     assert(Register::isPhysicalRegister(Reg) &&
466            "Not expecting virtual register!");
467 
468     if (!MO.isDef()) {
469       if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
470         // If it's using a non-loop-invariant register, then it's obviously not
471         // safe to hoist.
472         HasNonInvariantUse = true;
473       continue;
474     }
475 
476     if (MO.isImplicit()) {
477       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
478         PhysRegClobbers.set(*AI);
479       if (!MO.isDead())
480         // Non-dead implicit def? This cannot be hoisted.
481         RuledOut = true;
482       // No need to check if a dead implicit def is also defined by
483       // another instruction.
484       continue;
485     }
486 
487     // FIXME: For now, avoid instructions with multiple defs, unless
488     // it's a dead implicit def.
489     if (Def)
490       RuledOut = true;
491     else
492       Def = Reg;
493 
494     // If we have already seen another instruction that defines the same
495     // register, then this is not safe.  Two defs is indicated by setting a
496     // PhysRegClobbers bit.
497     for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
498       if (PhysRegDefs.test(*AS))
499         PhysRegClobbers.set(*AS);
500     }
501     // Need a second loop because MCRegAliasIterator can visit the same
502     // register twice.
503     for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS)
504       PhysRegDefs.set(*AS);
505 
506     if (PhysRegClobbers.test(Reg))
507       // MI defined register is seen defined by another instruction in
508       // the loop, it cannot be a LICM candidate.
509       RuledOut = true;
510   }
511 
512   // Only consider reloads for now and remats which do not have register
513   // operands. FIXME: Consider unfold load folding instructions.
514   if (Def && !RuledOut) {
515     int FI = std::numeric_limits<int>::min();
516     if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
517         (TII->isLoadFromStackSlot(*MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
518       Candidates.push_back(CandidateInfo(MI, Def, FI));
519   }
520 }
521 
522 /// Walk the specified region of the CFG and hoist loop invariants out to the
523 /// preheader.
524 void MachineLICMBase::HoistRegionPostRA() {
525   MachineBasicBlock *Preheader = getCurPreheader();
526   if (!Preheader)
527     return;
528 
529   unsigned NumRegs = TRI->getNumRegs();
530   BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
531   BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
532 
533   SmallVector<CandidateInfo, 32> Candidates;
534   SmallSet<int, 32> StoredFIs;
535 
536   // Walk the entire region, count number of defs for each register, and
537   // collect potential LICM candidates.
538   for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
539     // If the header of the loop containing this basic block is a landing pad,
540     // then don't try to hoist instructions out of this loop.
541     const MachineLoop *ML = MLI->getLoopFor(BB);
542     if (ML && ML->getHeader()->isEHPad()) continue;
543 
544     // Conservatively treat live-in's as an external def.
545     // FIXME: That means a reload that're reused in successor block(s) will not
546     // be LICM'ed.
547     for (const auto &LI : BB->liveins()) {
548       for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI)
549         PhysRegDefs.set(*AI);
550     }
551 
552     SpeculationState = SpeculateUnknown;
553     for (MachineInstr &MI : *BB)
554       ProcessMI(&MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
555   }
556 
557   // Gather the registers read / clobbered by the terminator.
558   BitVector TermRegs(NumRegs);
559   MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
560   if (TI != Preheader->end()) {
561     for (const MachineOperand &MO : TI->operands()) {
562       if (!MO.isReg())
563         continue;
564       Register Reg = MO.getReg();
565       if (!Reg)
566         continue;
567       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
568         TermRegs.set(*AI);
569     }
570   }
571 
572   // Now evaluate whether the potential candidates qualify.
573   // 1. Check if the candidate defined register is defined by another
574   //    instruction in the loop.
575   // 2. If the candidate is a load from stack slot (always true for now),
576   //    check if the slot is stored anywhere in the loop.
577   // 3. Make sure candidate def should not clobber
578   //    registers read by the terminator. Similarly its def should not be
579   //    clobbered by the terminator.
580   for (CandidateInfo &Candidate : Candidates) {
581     if (Candidate.FI != std::numeric_limits<int>::min() &&
582         StoredFIs.count(Candidate.FI))
583       continue;
584 
585     unsigned Def = Candidate.Def;
586     if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
587       bool Safe = true;
588       MachineInstr *MI = Candidate.MI;
589       for (const MachineOperand &MO : MI->operands()) {
590         if (!MO.isReg() || MO.isDef() || !MO.getReg())
591           continue;
592         Register Reg = MO.getReg();
593         if (PhysRegDefs.test(Reg) ||
594             PhysRegClobbers.test(Reg)) {
595           // If it's using a non-loop-invariant register, then it's obviously
596           // not safe to hoist.
597           Safe = false;
598           break;
599         }
600       }
601       if (Safe)
602         HoistPostRA(MI, Candidate.Def);
603     }
604   }
605 }
606 
607 /// Add register 'Reg' to the livein sets of BBs in the current loop, and make
608 /// sure it is not killed by any instructions in the loop.
609 void MachineLICMBase::AddToLiveIns(unsigned Reg) {
610   for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
611     if (!BB->isLiveIn(Reg))
612       BB->addLiveIn(Reg);
613     for (MachineInstr &MI : *BB) {
614       for (MachineOperand &MO : MI.operands()) {
615         if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
616         if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
617           MO.setIsKill(false);
618       }
619     }
620   }
621 }
622 
623 /// When an instruction is found to only use loop invariant operands that is
624 /// safe to hoist, this instruction is called to do the dirty work.
625 void MachineLICMBase::HoistPostRA(MachineInstr *MI, unsigned Def) {
626   MachineBasicBlock *Preheader = getCurPreheader();
627 
628   // Now move the instructions to the predecessor, inserting it before any
629   // terminator instructions.
630   LLVM_DEBUG(dbgs() << "Hoisting to " << printMBBReference(*Preheader)
631                     << " from " << printMBBReference(*MI->getParent()) << ": "
632                     << *MI);
633 
634   // Splice the instruction to the preheader.
635   MachineBasicBlock *MBB = MI->getParent();
636   Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
637 
638   // Since we are moving the instruction out of its basic block, we do not
639   // retain its debug location. Doing so would degrade the debugging
640   // experience and adversely affect the accuracy of profiling information.
641   assert(!MI->isDebugInstr() && "Should not hoist debug inst");
642   MI->setDebugLoc(DebugLoc());
643 
644   // Add register to livein list to all the BBs in the current loop since a
645   // loop invariant must be kept live throughout the whole loop. This is
646   // important to ensure later passes do not scavenge the def register.
647   AddToLiveIns(Def);
648 
649   ++NumPostRAHoisted;
650   Changed = true;
651 }
652 
653 /// Check if this mbb is guaranteed to execute. If not then a load from this mbb
654 /// may not be safe to hoist.
655 bool MachineLICMBase::IsGuaranteedToExecute(MachineBasicBlock *BB) {
656   if (SpeculationState != SpeculateUnknown)
657     return SpeculationState == SpeculateFalse;
658 
659   if (BB != CurLoop->getHeader()) {
660     // Check loop exiting blocks.
661     SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
662     CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
663     for (MachineBasicBlock *CurrentLoopExitingBlock : CurrentLoopExitingBlocks)
664       if (!DT->dominates(BB, CurrentLoopExitingBlock)) {
665         SpeculationState = SpeculateTrue;
666         return false;
667       }
668   }
669 
670   SpeculationState = SpeculateFalse;
671   return true;
672 }
673 
674 void MachineLICMBase::EnterScope(MachineBasicBlock *MBB) {
675   LLVM_DEBUG(dbgs() << "Entering " << printMBBReference(*MBB) << '\n');
676 
677   // Remember livein register pressure.
678   BackTrace.push_back(RegPressure);
679 }
680 
681 void MachineLICMBase::ExitScope(MachineBasicBlock *MBB) {
682   LLVM_DEBUG(dbgs() << "Exiting " << printMBBReference(*MBB) << '\n');
683   BackTrace.pop_back();
684 }
685 
686 /// Destroy scope for the MBB that corresponds to the given dominator tree node
687 /// if its a leaf or all of its children are done. Walk up the dominator tree to
688 /// destroy ancestors which are now done.
689 void MachineLICMBase::ExitScopeIfDone(MachineDomTreeNode *Node,
690     DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
691     DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
692   if (OpenChildren[Node])
693     return;
694 
695   // Pop scope.
696   ExitScope(Node->getBlock());
697 
698   // Now traverse upwards to pop ancestors whose offsprings are all done.
699   while (MachineDomTreeNode *Parent = ParentMap[Node]) {
700     unsigned Left = --OpenChildren[Parent];
701     if (Left != 0)
702       break;
703     ExitScope(Parent->getBlock());
704     Node = Parent;
705   }
706 }
707 
708 /// Walk the specified loop in the CFG (defined by all blocks dominated by the
709 /// specified header block, and that are in the current loop) in depth first
710 /// order w.r.t the DominatorTree. This allows us to visit definitions before
711 /// uses, allowing us to hoist a loop body in one pass without iteration.
712 void MachineLICMBase::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
713   MachineBasicBlock *Preheader = getCurPreheader();
714   if (!Preheader)
715     return;
716 
717   SmallVector<MachineDomTreeNode*, 32> Scopes;
718   SmallVector<MachineDomTreeNode*, 8> WorkList;
719   DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
720   DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
721 
722   // Perform a DFS walk to determine the order of visit.
723   WorkList.push_back(HeaderN);
724   while (!WorkList.empty()) {
725     MachineDomTreeNode *Node = WorkList.pop_back_val();
726     assert(Node && "Null dominator tree node?");
727     MachineBasicBlock *BB = Node->getBlock();
728 
729     // If the header of the loop containing this basic block is a landing pad,
730     // then don't try to hoist instructions out of this loop.
731     const MachineLoop *ML = MLI->getLoopFor(BB);
732     if (ML && ML->getHeader()->isEHPad())
733       continue;
734 
735     // If this subregion is not in the top level loop at all, exit.
736     if (!CurLoop->contains(BB))
737       continue;
738 
739     Scopes.push_back(Node);
740     unsigned NumChildren = Node->getNumChildren();
741 
742     // Don't hoist things out of a large switch statement.  This often causes
743     // code to be hoisted that wasn't going to be executed, and increases
744     // register pressure in a situation where it's likely to matter.
745     if (BB->succ_size() >= 25)
746       NumChildren = 0;
747 
748     OpenChildren[Node] = NumChildren;
749     if (NumChildren) {
750       // Add children in reverse order as then the next popped worklist node is
751       // the first child of this node.  This means we ultimately traverse the
752       // DOM tree in exactly the same order as if we'd recursed.
753       for (MachineDomTreeNode *Child : reverse(Node->children())) {
754         ParentMap[Child] = Node;
755         WorkList.push_back(Child);
756       }
757     }
758   }
759 
760   if (Scopes.size() == 0)
761     return;
762 
763   // Compute registers which are livein into the loop headers.
764   RegSeen.clear();
765   BackTrace.clear();
766   InitRegPressure(Preheader);
767 
768   // Now perform LICM.
769   for (MachineDomTreeNode *Node : Scopes) {
770     MachineBasicBlock *MBB = Node->getBlock();
771 
772     EnterScope(MBB);
773 
774     // Process the block
775     SpeculationState = SpeculateUnknown;
776     for (MachineBasicBlock::iterator
777          MII = MBB->begin(), E = MBB->end(); MII != E; ) {
778       MachineBasicBlock::iterator NextMII = MII; ++NextMII;
779       MachineInstr *MI = &*MII;
780       if (!Hoist(MI, Preheader))
781         UpdateRegPressure(MI);
782       // If we have hoisted an instruction that may store, it can only be a
783       // constant store.
784       MII = NextMII;
785     }
786 
787     // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
788     ExitScopeIfDone(Node, OpenChildren, ParentMap);
789   }
790 }
791 
792 /// Sink instructions into loops if profitable. This especially tries to prevent
793 /// register spills caused by register pressure if there is little to no
794 /// overhead moving instructions into loops.
795 void MachineLICMBase::SinkIntoLoop() {
796   MachineBasicBlock *Preheader = getCurPreheader();
797   if (!Preheader)
798     return;
799 
800   SmallVector<MachineInstr *, 8> Candidates;
801   for (MachineBasicBlock::instr_iterator I = Preheader->instr_begin();
802        I != Preheader->instr_end(); ++I) {
803     // We need to ensure that we can safely move this instruction into the loop.
804     // As such, it must not have side-effects, e.g. such as a call has.
805     if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(&*I))
806       Candidates.push_back(&*I);
807   }
808 
809   for (MachineInstr *I : Candidates) {
810     const MachineOperand &MO = I->getOperand(0);
811     if (!MO.isDef() || !MO.isReg() || !MO.getReg())
812       continue;
813     if (!MRI->hasOneDef(MO.getReg()))
814       continue;
815     bool CanSink = true;
816     MachineBasicBlock *B = nullptr;
817     for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
818       // FIXME: Come up with a proper cost model that estimates whether sinking
819       // the instruction (and thus possibly executing it on every loop
820       // iteration) is more expensive than a register.
821       // For now assumes that copies are cheap and thus almost always worth it.
822       if (!MI.isCopy()) {
823         CanSink = false;
824         break;
825       }
826       if (!B) {
827         B = MI.getParent();
828         continue;
829       }
830       B = DT->findNearestCommonDominator(B, MI.getParent());
831       if (!B) {
832         CanSink = false;
833         break;
834       }
835     }
836     if (!CanSink || !B || B == Preheader)
837       continue;
838 
839     LLVM_DEBUG(dbgs() << "Sinking to " << printMBBReference(*B) << " from "
840                       << printMBBReference(*I->getParent()) << ": " << *I);
841     B->splice(B->getFirstNonPHI(), Preheader, I);
842 
843     // The instruction is is moved from its basic block, so do not retain the
844     // debug information.
845     assert(!I->isDebugInstr() && "Should not sink debug inst");
846     I->setDebugLoc(DebugLoc());
847   }
848 }
849 
850 static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
851   return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
852 }
853 
854 /// Find all virtual register references that are liveout of the preheader to
855 /// initialize the starting "register pressure". Note this does not count live
856 /// through (livein but not used) registers.
857 void MachineLICMBase::InitRegPressure(MachineBasicBlock *BB) {
858   std::fill(RegPressure.begin(), RegPressure.end(), 0);
859 
860   // If the preheader has only a single predecessor and it ends with a
861   // fallthrough or an unconditional branch, then scan its predecessor for live
862   // defs as well. This happens whenever the preheader is created by splitting
863   // the critical edge from the loop predecessor to the loop header.
864   if (BB->pred_size() == 1) {
865     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
866     SmallVector<MachineOperand, 4> Cond;
867     if (!TII->analyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
868       InitRegPressure(*BB->pred_begin());
869   }
870 
871   for (const MachineInstr &MI : *BB)
872     UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
873 }
874 
875 /// Update estimate of register pressure after the specified instruction.
876 void MachineLICMBase::UpdateRegPressure(const MachineInstr *MI,
877                                         bool ConsiderUnseenAsDef) {
878   auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
879   for (const auto &RPIdAndCost : Cost) {
880     unsigned Class = RPIdAndCost.first;
881     if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second)
882       RegPressure[Class] = 0;
883     else
884       RegPressure[Class] += RPIdAndCost.second;
885   }
886 }
887 
888 /// Calculate the additional register pressure that the registers used in MI
889 /// cause.
890 ///
891 /// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
892 /// figure out which usages are live-ins.
893 /// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
894 DenseMap<unsigned, int>
895 MachineLICMBase::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
896                                   bool ConsiderUnseenAsDef) {
897   DenseMap<unsigned, int> Cost;
898   if (MI->isImplicitDef())
899     return Cost;
900   for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
901     const MachineOperand &MO = MI->getOperand(i);
902     if (!MO.isReg() || MO.isImplicit())
903       continue;
904     Register Reg = MO.getReg();
905     if (!Register::isVirtualRegister(Reg))
906       continue;
907 
908     // FIXME: It seems bad to use RegSeen only for some of these calculations.
909     bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
910     const TargetRegisterClass *RC = MRI->getRegClass(Reg);
911 
912     RegClassWeight W = TRI->getRegClassWeight(RC);
913     int RCCost = 0;
914     if (MO.isDef())
915       RCCost = W.RegWeight;
916     else {
917       bool isKill = isOperandKill(MO, MRI);
918       if (isNew && !isKill && ConsiderUnseenAsDef)
919         // Haven't seen this, it must be a livein.
920         RCCost = W.RegWeight;
921       else if (!isNew && isKill)
922         RCCost = -W.RegWeight;
923     }
924     if (RCCost == 0)
925       continue;
926     const int *PS = TRI->getRegClassPressureSets(RC);
927     for (; *PS != -1; ++PS) {
928       if (Cost.find(*PS) == Cost.end())
929         Cost[*PS] = RCCost;
930       else
931         Cost[*PS] += RCCost;
932     }
933   }
934   return Cost;
935 }
936 
937 /// Return true if this machine instruction loads from global offset table or
938 /// constant pool.
939 static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
940   assert(MI.mayLoad() && "Expected MI that loads!");
941 
942   // If we lost memory operands, conservatively assume that the instruction
943   // reads from everything..
944   if (MI.memoperands_empty())
945     return true;
946 
947   for (MachineMemOperand *MemOp : MI.memoperands())
948     if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
949       if (PSV->isGOT() || PSV->isConstantPool())
950         return true;
951 
952   return false;
953 }
954 
955 // This function iterates through all the operands of the input store MI and
956 // checks that each register operand statisfies isCallerPreservedPhysReg.
957 // This means, the value being stored and the address where it is being stored
958 // is constant throughout the body of the function (not including prologue and
959 // epilogue). When called with an MI that isn't a store, it returns false.
960 // A future improvement can be to check if the store registers are constant
961 // throughout the loop rather than throughout the funtion.
962 static bool isInvariantStore(const MachineInstr &MI,
963                              const TargetRegisterInfo *TRI,
964                              const MachineRegisterInfo *MRI) {
965 
966   bool FoundCallerPresReg = false;
967   if (!MI.mayStore() || MI.hasUnmodeledSideEffects() ||
968       (MI.getNumOperands() == 0))
969     return false;
970 
971   // Check that all register operands are caller-preserved physical registers.
972   for (const MachineOperand &MO : MI.operands()) {
973     if (MO.isReg()) {
974       Register Reg = MO.getReg();
975       // If operand is a virtual register, check if it comes from a copy of a
976       // physical register.
977       if (Register::isVirtualRegister(Reg))
978         Reg = TRI->lookThruCopyLike(MO.getReg(), MRI);
979       if (Register::isVirtualRegister(Reg))
980         return false;
981       if (!TRI->isCallerPreservedPhysReg(Reg, *MI.getMF()))
982         return false;
983       else
984         FoundCallerPresReg = true;
985     } else if (!MO.isImm()) {
986         return false;
987     }
988   }
989   return FoundCallerPresReg;
990 }
991 
992 // Return true if the input MI is a copy instruction that feeds an invariant
993 // store instruction. This means that the src of the copy has to satisfy
994 // isCallerPreservedPhysReg and atleast one of it's users should satisfy
995 // isInvariantStore.
996 static bool isCopyFeedingInvariantStore(const MachineInstr &MI,
997                                         const MachineRegisterInfo *MRI,
998                                         const TargetRegisterInfo *TRI) {
999 
1000   // FIXME: If targets would like to look through instructions that aren't
1001   // pure copies, this can be updated to a query.
1002   if (!MI.isCopy())
1003     return false;
1004 
1005   const MachineFunction *MF = MI.getMF();
1006   // Check that we are copying a constant physical register.
1007   Register CopySrcReg = MI.getOperand(1).getReg();
1008   if (Register::isVirtualRegister(CopySrcReg))
1009     return false;
1010 
1011   if (!TRI->isCallerPreservedPhysReg(CopySrcReg, *MF))
1012     return false;
1013 
1014   Register CopyDstReg = MI.getOperand(0).getReg();
1015   // Check if any of the uses of the copy are invariant stores.
1016   assert(Register::isVirtualRegister(CopyDstReg) &&
1017          "copy dst is not a virtual reg");
1018 
1019   for (MachineInstr &UseMI : MRI->use_instructions(CopyDstReg)) {
1020     if (UseMI.mayStore() && isInvariantStore(UseMI, TRI, MRI))
1021       return true;
1022   }
1023   return false;
1024 }
1025 
1026 /// Returns true if the instruction may be a suitable candidate for LICM.
1027 /// e.g. If the instruction is a call, then it's obviously not safe to hoist it.
1028 bool MachineLICMBase::IsLICMCandidate(MachineInstr &I) {
1029   // Check if it's safe to move the instruction.
1030   bool DontMoveAcrossStore = true;
1031   if ((!I.isSafeToMove(AA, DontMoveAcrossStore)) &&
1032       !(HoistConstStores && isInvariantStore(I, TRI, MRI))) {
1033     return false;
1034   }
1035 
1036   // If it is load then check if it is guaranteed to execute by making sure that
1037   // it dominates all exiting blocks. If it doesn't, then there is a path out of
1038   // the loop which does not execute this load, so we can't hoist it. Loads
1039   // from constant memory are not safe to speculate all the time, for example
1040   // indexed load from a jump table.
1041   // Stores and side effects are already checked by isSafeToMove.
1042   if (I.mayLoad() && !mayLoadFromGOTOrConstantPool(I) &&
1043       !IsGuaranteedToExecute(I.getParent()))
1044     return false;
1045 
1046   return true;
1047 }
1048 
1049 /// Returns true if the instruction is loop invariant.
1050 /// I.e., all virtual register operands are defined outside of the loop,
1051 /// physical registers aren't accessed explicitly, and there are no side
1052 /// effects that aren't captured by the operands or other flags.
1053 bool MachineLICMBase::IsLoopInvariantInst(MachineInstr &I) {
1054   if (!IsLICMCandidate(I))
1055     return false;
1056 
1057   // The instruction is loop invariant if all of its operands are.
1058   for (const MachineOperand &MO : I.operands()) {
1059     if (!MO.isReg())
1060       continue;
1061 
1062     Register Reg = MO.getReg();
1063     if (Reg == 0) continue;
1064 
1065     // Don't hoist an instruction that uses or defines a physical register.
1066     if (Register::isPhysicalRegister(Reg)) {
1067       if (MO.isUse()) {
1068         // If the physreg has no defs anywhere, it's just an ambient register
1069         // and we can freely move its uses. Alternatively, if it's allocatable,
1070         // it could get allocated to something with a def during allocation.
1071         // However, if the physreg is known to always be caller saved/restored
1072         // then this use is safe to hoist.
1073         if (!MRI->isConstantPhysReg(Reg) &&
1074             !(TRI->isCallerPreservedPhysReg(Reg, *I.getMF())))
1075           return false;
1076         // Otherwise it's safe to move.
1077         continue;
1078       } else if (!MO.isDead()) {
1079         // A def that isn't dead. We can't move it.
1080         return false;
1081       } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
1082         // If the reg is live into the loop, we can't hoist an instruction
1083         // which would clobber it.
1084         return false;
1085       }
1086     }
1087 
1088     if (!MO.isUse())
1089       continue;
1090 
1091     assert(MRI->getVRegDef(Reg) &&
1092            "Machine instr not mapped for this vreg?!");
1093 
1094     // If the loop contains the definition of an operand, then the instruction
1095     // isn't loop invariant.
1096     if (CurLoop->contains(MRI->getVRegDef(Reg)))
1097       return false;
1098   }
1099 
1100   // If we got this far, the instruction is loop invariant!
1101   return true;
1102 }
1103 
1104 /// Return true if the specified instruction is used by a phi node and hoisting
1105 /// it could cause a copy to be inserted.
1106 bool MachineLICMBase::HasLoopPHIUse(const MachineInstr *MI) const {
1107   SmallVector<const MachineInstr*, 8> Work(1, MI);
1108   do {
1109     MI = Work.pop_back_val();
1110     for (const MachineOperand &MO : MI->operands()) {
1111       if (!MO.isReg() || !MO.isDef())
1112         continue;
1113       Register Reg = MO.getReg();
1114       if (!Register::isVirtualRegister(Reg))
1115         continue;
1116       for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
1117         // A PHI may cause a copy to be inserted.
1118         if (UseMI.isPHI()) {
1119           // A PHI inside the loop causes a copy because the live range of Reg is
1120           // extended across the PHI.
1121           if (CurLoop->contains(&UseMI))
1122             return true;
1123           // A PHI in an exit block can cause a copy to be inserted if the PHI
1124           // has multiple predecessors in the loop with different values.
1125           // For now, approximate by rejecting all exit blocks.
1126           if (isExitBlock(UseMI.getParent()))
1127             return true;
1128           continue;
1129         }
1130         // Look past copies as well.
1131         if (UseMI.isCopy() && CurLoop->contains(&UseMI))
1132           Work.push_back(&UseMI);
1133       }
1134     }
1135   } while (!Work.empty());
1136   return false;
1137 }
1138 
1139 /// Compute operand latency between a def of 'Reg' and an use in the current
1140 /// loop, return true if the target considered it high.
1141 bool MachineLICMBase::HasHighOperandLatency(MachineInstr &MI,
1142                                             unsigned DefIdx,
1143                                             unsigned Reg) const {
1144   if (MRI->use_nodbg_empty(Reg))
1145     return false;
1146 
1147   for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
1148     if (UseMI.isCopyLike())
1149       continue;
1150     if (!CurLoop->contains(UseMI.getParent()))
1151       continue;
1152     for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
1153       const MachineOperand &MO = UseMI.getOperand(i);
1154       if (!MO.isReg() || !MO.isUse())
1155         continue;
1156       Register MOReg = MO.getReg();
1157       if (MOReg != Reg)
1158         continue;
1159 
1160       if (TII->hasHighOperandLatency(SchedModel, MRI, MI, DefIdx, UseMI, i))
1161         return true;
1162     }
1163 
1164     // Only look at the first in loop use.
1165     break;
1166   }
1167 
1168   return false;
1169 }
1170 
1171 /// Return true if the instruction is marked "cheap" or the operand latency
1172 /// between its def and a use is one or less.
1173 bool MachineLICMBase::IsCheapInstruction(MachineInstr &MI) const {
1174   if (TII->isAsCheapAsAMove(MI) || MI.isCopyLike())
1175     return true;
1176 
1177   bool isCheap = false;
1178   unsigned NumDefs = MI.getDesc().getNumDefs();
1179   for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1180     MachineOperand &DefMO = MI.getOperand(i);
1181     if (!DefMO.isReg() || !DefMO.isDef())
1182       continue;
1183     --NumDefs;
1184     Register Reg = DefMO.getReg();
1185     if (Register::isPhysicalRegister(Reg))
1186       continue;
1187 
1188     if (!TII->hasLowDefLatency(SchedModel, MI, i))
1189       return false;
1190     isCheap = true;
1191   }
1192 
1193   return isCheap;
1194 }
1195 
1196 /// Visit BBs from header to current BB, check if hoisting an instruction of the
1197 /// given cost matrix can cause high register pressure.
1198 bool
1199 MachineLICMBase::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
1200                                          bool CheapInstr) {
1201   for (const auto &RPIdAndCost : Cost) {
1202     if (RPIdAndCost.second <= 0)
1203       continue;
1204 
1205     unsigned Class = RPIdAndCost.first;
1206     int Limit = RegLimit[Class];
1207 
1208     // Don't hoist cheap instructions if they would increase register pressure,
1209     // even if we're under the limit.
1210     if (CheapInstr && !HoistCheapInsts)
1211       return true;
1212 
1213     for (const auto &RP : BackTrace)
1214       if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit)
1215         return true;
1216   }
1217 
1218   return false;
1219 }
1220 
1221 /// Traverse the back trace from header to the current block and update their
1222 /// register pressures to reflect the effect of hoisting MI from the current
1223 /// block to the preheader.
1224 void MachineLICMBase::UpdateBackTraceRegPressure(const MachineInstr *MI) {
1225   // First compute the 'cost' of the instruction, i.e. its contribution
1226   // to register pressure.
1227   auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
1228                                /*ConsiderUnseenAsDef=*/false);
1229 
1230   // Update register pressure of blocks from loop header to current block.
1231   for (auto &RP : BackTrace)
1232     for (const auto &RPIdAndCost : Cost)
1233       RP[RPIdAndCost.first] += RPIdAndCost.second;
1234 }
1235 
1236 /// Return true if it is potentially profitable to hoist the given loop
1237 /// invariant.
1238 bool MachineLICMBase::IsProfitableToHoist(MachineInstr &MI) {
1239   if (MI.isImplicitDef())
1240     return true;
1241 
1242   // Besides removing computation from the loop, hoisting an instruction has
1243   // these effects:
1244   //
1245   // - The value defined by the instruction becomes live across the entire
1246   //   loop. This increases register pressure in the loop.
1247   //
1248   // - If the value is used by a PHI in the loop, a copy will be required for
1249   //   lowering the PHI after extending the live range.
1250   //
1251   // - When hoisting the last use of a value in the loop, that value no longer
1252   //   needs to be live in the loop. This lowers register pressure in the loop.
1253 
1254   if (HoistConstStores &&  isCopyFeedingInvariantStore(MI, MRI, TRI))
1255     return true;
1256 
1257   bool CheapInstr = IsCheapInstruction(MI);
1258   bool CreatesCopy = HasLoopPHIUse(&MI);
1259 
1260   // Don't hoist a cheap instruction if it would create a copy in the loop.
1261   if (CheapInstr && CreatesCopy) {
1262     LLVM_DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1263     return false;
1264   }
1265 
1266   // Rematerializable instructions should always be hoisted since the register
1267   // allocator can just pull them down again when needed.
1268   if (TII->isTriviallyReMaterializable(MI, AA))
1269     return true;
1270 
1271   // FIXME: If there are long latency loop-invariant instructions inside the
1272   // loop at this point, why didn't the optimizer's LICM hoist them?
1273   for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1274     const MachineOperand &MO = MI.getOperand(i);
1275     if (!MO.isReg() || MO.isImplicit())
1276       continue;
1277     Register Reg = MO.getReg();
1278     if (!Register::isVirtualRegister(Reg))
1279       continue;
1280     if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) {
1281       LLVM_DEBUG(dbgs() << "Hoist High Latency: " << MI);
1282       ++NumHighLatency;
1283       return true;
1284     }
1285   }
1286 
1287   // Estimate register pressure to determine whether to LICM the instruction.
1288   // In low register pressure situation, we can be more aggressive about
1289   // hoisting. Also, favors hoisting long latency instructions even in
1290   // moderately high pressure situation.
1291   // Cheap instructions will only be hoisted if they don't increase register
1292   // pressure at all.
1293   auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
1294                                /*ConsiderUnseenAsDef=*/false);
1295 
1296   // Visit BBs from header to current BB, if hoisting this doesn't cause
1297   // high register pressure, then it's safe to proceed.
1298   if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1299     LLVM_DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1300     ++NumLowRP;
1301     return true;
1302   }
1303 
1304   // Don't risk increasing register pressure if it would create copies.
1305   if (CreatesCopy) {
1306     LLVM_DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
1307     return false;
1308   }
1309 
1310   // Do not "speculate" in high register pressure situation. If an
1311   // instruction is not guaranteed to be executed in the loop, it's best to be
1312   // conservative.
1313   if (AvoidSpeculation &&
1314       (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
1315     LLVM_DEBUG(dbgs() << "Won't speculate: " << MI);
1316     return false;
1317   }
1318 
1319   // High register pressure situation, only hoist if the instruction is going
1320   // to be remat'ed.
1321   if (!TII->isTriviallyReMaterializable(MI, AA) &&
1322       !MI.isDereferenceableInvariantLoad(AA)) {
1323     LLVM_DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1324     return false;
1325   }
1326 
1327   return true;
1328 }
1329 
1330 /// Unfold a load from the given machineinstr if the load itself could be
1331 /// hoisted. Return the unfolded and hoistable load, or null if the load
1332 /// couldn't be unfolded or if it wouldn't be hoistable.
1333 MachineInstr *MachineLICMBase::ExtractHoistableLoad(MachineInstr *MI) {
1334   // Don't unfold simple loads.
1335   if (MI->canFoldAsLoad())
1336     return nullptr;
1337 
1338   // If not, we may be able to unfold a load and hoist that.
1339   // First test whether the instruction is loading from an amenable
1340   // memory location.
1341   if (!MI->isDereferenceableInvariantLoad(AA))
1342     return nullptr;
1343 
1344   // Next determine the register class for a temporary register.
1345   unsigned LoadRegIndex;
1346   unsigned NewOpc =
1347     TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1348                                     /*UnfoldLoad=*/true,
1349                                     /*UnfoldStore=*/false,
1350                                     &LoadRegIndex);
1351   if (NewOpc == 0) return nullptr;
1352   const MCInstrDesc &MID = TII->get(NewOpc);
1353   MachineFunction &MF = *MI->getMF();
1354   const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
1355   // Ok, we're unfolding. Create a temporary register and do the unfold.
1356   Register Reg = MRI->createVirtualRegister(RC);
1357 
1358   SmallVector<MachineInstr *, 2> NewMIs;
1359   bool Success = TII->unfoldMemoryOperand(MF, *MI, Reg,
1360                                           /*UnfoldLoad=*/true,
1361                                           /*UnfoldStore=*/false, NewMIs);
1362   (void)Success;
1363   assert(Success &&
1364          "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1365          "succeeded!");
1366   assert(NewMIs.size() == 2 &&
1367          "Unfolded a load into multiple instructions!");
1368   MachineBasicBlock *MBB = MI->getParent();
1369   MachineBasicBlock::iterator Pos = MI;
1370   MBB->insert(Pos, NewMIs[0]);
1371   MBB->insert(Pos, NewMIs[1]);
1372   // If unfolding produced a load that wasn't loop-invariant or profitable to
1373   // hoist, discard the new instructions and bail.
1374   if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
1375     NewMIs[0]->eraseFromParent();
1376     NewMIs[1]->eraseFromParent();
1377     return nullptr;
1378   }
1379 
1380   // Update register pressure for the unfolded instruction.
1381   UpdateRegPressure(NewMIs[1]);
1382 
1383   // Otherwise we successfully unfolded a load that we can hoist.
1384 
1385   // Update the call site info.
1386   if (MI->shouldUpdateCallSiteInfo())
1387     MF.eraseCallSiteInfo(MI);
1388 
1389   MI->eraseFromParent();
1390   return NewMIs[0];
1391 }
1392 
1393 /// Initialize the CSE map with instructions that are in the current loop
1394 /// preheader that may become duplicates of instructions that are hoisted
1395 /// out of the loop.
1396 void MachineLICMBase::InitCSEMap(MachineBasicBlock *BB) {
1397   for (MachineInstr &MI : *BB)
1398     CSEMap[MI.getOpcode()].push_back(&MI);
1399 }
1400 
1401 /// Find an instruction amount PrevMIs that is a duplicate of MI.
1402 /// Return this instruction if it's found.
1403 const MachineInstr*
1404 MachineLICMBase::LookForDuplicate(const MachineInstr *MI,
1405                                   std::vector<const MachineInstr*> &PrevMIs) {
1406   for (const MachineInstr *PrevMI : PrevMIs)
1407     if (TII->produceSameValue(*MI, *PrevMI, (PreRegAlloc ? MRI : nullptr)))
1408       return PrevMI;
1409 
1410   return nullptr;
1411 }
1412 
1413 /// Given a LICM'ed instruction, look for an instruction on the preheader that
1414 /// computes the same value. If it's found, do a RAU on with the definition of
1415 /// the existing instruction rather than hoisting the instruction to the
1416 /// preheader.
1417 bool MachineLICMBase::EliminateCSE(MachineInstr *MI,
1418     DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI) {
1419   // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1420   // the undef property onto uses.
1421   if (CI == CSEMap.end() || MI->isImplicitDef())
1422     return false;
1423 
1424   if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
1425     LLVM_DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
1426 
1427     // Replace virtual registers defined by MI by their counterparts defined
1428     // by Dup.
1429     SmallVector<unsigned, 2> Defs;
1430     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1431       const MachineOperand &MO = MI->getOperand(i);
1432 
1433       // Physical registers may not differ here.
1434       assert((!MO.isReg() || MO.getReg() == 0 ||
1435               !Register::isPhysicalRegister(MO.getReg()) ||
1436               MO.getReg() == Dup->getOperand(i).getReg()) &&
1437              "Instructions with different phys regs are not identical!");
1438 
1439       if (MO.isReg() && MO.isDef() &&
1440           !Register::isPhysicalRegister(MO.getReg()))
1441         Defs.push_back(i);
1442     }
1443 
1444     SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1445     for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1446       unsigned Idx = Defs[i];
1447       Register Reg = MI->getOperand(Idx).getReg();
1448       Register DupReg = Dup->getOperand(Idx).getReg();
1449       OrigRCs.push_back(MRI->getRegClass(DupReg));
1450 
1451       if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1452         // Restore old RCs if more than one defs.
1453         for (unsigned j = 0; j != i; ++j)
1454           MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1455         return false;
1456       }
1457     }
1458 
1459     for (unsigned Idx : Defs) {
1460       Register Reg = MI->getOperand(Idx).getReg();
1461       Register DupReg = Dup->getOperand(Idx).getReg();
1462       MRI->replaceRegWith(Reg, DupReg);
1463       MRI->clearKillFlags(DupReg);
1464     }
1465 
1466     MI->eraseFromParent();
1467     ++NumCSEed;
1468     return true;
1469   }
1470   return false;
1471 }
1472 
1473 /// Return true if the given instruction will be CSE'd if it's hoisted out of
1474 /// the loop.
1475 bool MachineLICMBase::MayCSE(MachineInstr *MI) {
1476   unsigned Opcode = MI->getOpcode();
1477   DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator
1478     CI = CSEMap.find(Opcode);
1479   // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1480   // the undef property onto uses.
1481   if (CI == CSEMap.end() || MI->isImplicitDef())
1482     return false;
1483 
1484   return LookForDuplicate(MI, CI->second) != nullptr;
1485 }
1486 
1487 /// When an instruction is found to use only loop invariant operands
1488 /// that are safe to hoist, this instruction is called to do the dirty work.
1489 /// It returns true if the instruction is hoisted.
1490 bool MachineLICMBase::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
1491   MachineBasicBlock *SrcBlock = MI->getParent();
1492 
1493   // Disable the instruction hoisting due to block hotness
1494   if ((DisableHoistingToHotterBlocks == UseBFI::All ||
1495       (DisableHoistingToHotterBlocks == UseBFI::PGO && HasProfileData)) &&
1496       isTgtHotterThanSrc(SrcBlock, Preheader)) {
1497     ++NumNotHoistedDueToHotness;
1498     return false;
1499   }
1500   // First check whether we should hoist this instruction.
1501   if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
1502     // If not, try unfolding a hoistable load.
1503     MI = ExtractHoistableLoad(MI);
1504     if (!MI) return false;
1505   }
1506 
1507   // If we have hoisted an instruction that may store, it can only be a constant
1508   // store.
1509   if (MI->mayStore())
1510     NumStoreConst++;
1511 
1512   // Now move the instructions to the predecessor, inserting it before any
1513   // terminator instructions.
1514   LLVM_DEBUG({
1515     dbgs() << "Hoisting " << *MI;
1516     if (MI->getParent()->getBasicBlock())
1517       dbgs() << " from " << printMBBReference(*MI->getParent());
1518     if (Preheader->getBasicBlock())
1519       dbgs() << " to " << printMBBReference(*Preheader);
1520     dbgs() << "\n";
1521   });
1522 
1523   // If this is the first instruction being hoisted to the preheader,
1524   // initialize the CSE map with potential common expressions.
1525   if (FirstInLoop) {
1526     InitCSEMap(Preheader);
1527     FirstInLoop = false;
1528   }
1529 
1530   // Look for opportunity to CSE the hoisted instruction.
1531   unsigned Opcode = MI->getOpcode();
1532   DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator
1533     CI = CSEMap.find(Opcode);
1534   if (!EliminateCSE(MI, CI)) {
1535     // Otherwise, splice the instruction to the preheader.
1536     Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
1537 
1538     // Since we are moving the instruction out of its basic block, we do not
1539     // retain its debug location. Doing so would degrade the debugging
1540     // experience and adversely affect the accuracy of profiling information.
1541     assert(!MI->isDebugInstr() && "Should not hoist debug inst");
1542     MI->setDebugLoc(DebugLoc());
1543 
1544     // Update register pressure for BBs from header to this block.
1545     UpdateBackTraceRegPressure(MI);
1546 
1547     // Clear the kill flags of any register this instruction defines,
1548     // since they may need to be live throughout the entire loop
1549     // rather than just live for part of it.
1550     for (MachineOperand &MO : MI->operands())
1551       if (MO.isReg() && MO.isDef() && !MO.isDead())
1552         MRI->clearKillFlags(MO.getReg());
1553 
1554     // Add to the CSE map.
1555     if (CI != CSEMap.end())
1556       CI->second.push_back(MI);
1557     else
1558       CSEMap[Opcode].push_back(MI);
1559   }
1560 
1561   ++NumHoisted;
1562   Changed = true;
1563 
1564   return true;
1565 }
1566 
1567 /// Get the preheader for the current loop, splitting a critical edge if needed.
1568 MachineBasicBlock *MachineLICMBase::getCurPreheader() {
1569   // Determine the block to which to hoist instructions. If we can't find a
1570   // suitable loop predecessor, we can't do any hoisting.
1571 
1572   // If we've tried to get a preheader and failed, don't try again.
1573   if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1574     return nullptr;
1575 
1576   if (!CurPreheader) {
1577     CurPreheader = CurLoop->getLoopPreheader();
1578     if (!CurPreheader) {
1579       MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1580       if (!Pred) {
1581         CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1582         return nullptr;
1583       }
1584 
1585       CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), *this);
1586       if (!CurPreheader) {
1587         CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1588         return nullptr;
1589       }
1590     }
1591   }
1592   return CurPreheader;
1593 }
1594 
1595 /// Is the target basic block at least "BlockFrequencyRatioThreshold"
1596 /// times hotter than the source basic block.
1597 bool MachineLICMBase::isTgtHotterThanSrc(MachineBasicBlock *SrcBlock,
1598                                          MachineBasicBlock *TgtBlock) {
1599   // Parse source and target basic block frequency from MBFI
1600   uint64_t SrcBF = MBFI->getBlockFreq(SrcBlock).getFrequency();
1601   uint64_t DstBF = MBFI->getBlockFreq(TgtBlock).getFrequency();
1602 
1603   // Disable the hoisting if source block frequency is zero
1604   if (!SrcBF)
1605     return true;
1606 
1607   double Ratio = (double)DstBF / SrcBF;
1608 
1609   // Compare the block frequency ratio with the threshold
1610   return Ratio > BlockFrequencyRatioThreshold;
1611 }
1612