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