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(true), 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);
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   // Check mayStore before memory operands so that e.g. DBG_VALUEs will return
378   // true since they have no memory operands.
379   if (!MI->mayStore())
380      return false;
381   // If we lost memory operands, conservatively assume that the instruction
382   // writes to all slots.
383   if (MI->memoperands_empty())
384     return true;
385   for (const MachineMemOperand *MemOp : MI->memoperands()) {
386     if (!MemOp->isStore() || !MemOp->getPseudoValue())
387       continue;
388     if (const FixedStackPseudoSourceValue *Value =
389         dyn_cast<FixedStackPseudoSourceValue>(MemOp->getPseudoValue())) {
390       if (Value->getFrameIndex() == FI)
391         return true;
392     }
393   }
394   return false;
395 }
396 
397 /// Examine the instruction for potentai LICM candidate. Also
398 /// gather register def and frame object update information.
399 void MachineLICMBase::ProcessMI(MachineInstr *MI,
400                                 BitVector &PhysRegDefs,
401                                 BitVector &PhysRegClobbers,
402                                 SmallSet<int, 32> &StoredFIs,
403                                 SmallVectorImpl<CandidateInfo> &Candidates) {
404   bool RuledOut = false;
405   bool HasNonInvariantUse = false;
406   unsigned Def = 0;
407   for (const MachineOperand &MO : MI->operands()) {
408     if (MO.isFI()) {
409       // Remember if the instruction stores to the frame index.
410       int FI = MO.getIndex();
411       if (!StoredFIs.count(FI) &&
412           MFI->isSpillSlotObjectIndex(FI) &&
413           InstructionStoresToFI(MI, FI))
414         StoredFIs.insert(FI);
415       HasNonInvariantUse = true;
416       continue;
417     }
418 
419     // We can't hoist an instruction defining a physreg that is clobbered in
420     // the loop.
421     if (MO.isRegMask()) {
422       PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
423       continue;
424     }
425 
426     if (!MO.isReg())
427       continue;
428     unsigned Reg = MO.getReg();
429     if (!Reg)
430       continue;
431     assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
432            "Not expecting virtual register!");
433 
434     if (!MO.isDef()) {
435       if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
436         // If it's using a non-loop-invariant register, then it's obviously not
437         // safe to hoist.
438         HasNonInvariantUse = true;
439       continue;
440     }
441 
442     if (MO.isImplicit()) {
443       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
444         PhysRegClobbers.set(*AI);
445       if (!MO.isDead())
446         // Non-dead implicit def? This cannot be hoisted.
447         RuledOut = true;
448       // No need to check if a dead implicit def is also defined by
449       // another instruction.
450       continue;
451     }
452 
453     // FIXME: For now, avoid instructions with multiple defs, unless
454     // it's a dead implicit def.
455     if (Def)
456       RuledOut = true;
457     else
458       Def = Reg;
459 
460     // If we have already seen another instruction that defines the same
461     // register, then this is not safe.  Two defs is indicated by setting a
462     // PhysRegClobbers bit.
463     for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
464       if (PhysRegDefs.test(*AS))
465         PhysRegClobbers.set(*AS);
466       PhysRegDefs.set(*AS);
467     }
468     if (PhysRegClobbers.test(Reg))
469       // MI defined register is seen defined by another instruction in
470       // the loop, it cannot be a LICM candidate.
471       RuledOut = true;
472   }
473 
474   // Only consider reloads for now and remats which do not have register
475   // operands. FIXME: Consider unfold load folding instructions.
476   if (Def && !RuledOut) {
477     int FI = std::numeric_limits<int>::min();
478     if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
479         (TII->isLoadFromStackSlot(*MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
480       Candidates.push_back(CandidateInfo(MI, Def, FI));
481   }
482 }
483 
484 /// Walk the specified region of the CFG and hoist loop invariants out to the
485 /// preheader.
486 void MachineLICMBase::HoistRegionPostRA() {
487   MachineBasicBlock *Preheader = getCurPreheader();
488   if (!Preheader)
489     return;
490 
491   unsigned NumRegs = TRI->getNumRegs();
492   BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
493   BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
494 
495   SmallVector<CandidateInfo, 32> Candidates;
496   SmallSet<int, 32> StoredFIs;
497 
498   // Walk the entire region, count number of defs for each register, and
499   // collect potential LICM candidates.
500   const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
501   for (MachineBasicBlock *BB : Blocks) {
502     // If the header of the loop containing this basic block is a landing pad,
503     // then don't try to hoist instructions out of this loop.
504     const MachineLoop *ML = MLI->getLoopFor(BB);
505     if (ML && ML->getHeader()->isEHPad()) continue;
506 
507     // Conservatively treat live-in's as an external def.
508     // FIXME: That means a reload that're reused in successor block(s) will not
509     // be LICM'ed.
510     for (const auto &LI : BB->liveins()) {
511       for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI)
512         PhysRegDefs.set(*AI);
513     }
514 
515     SpeculationState = SpeculateUnknown;
516     for (MachineInstr &MI : *BB)
517       ProcessMI(&MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
518   }
519 
520   // Gather the registers read / clobbered by the terminator.
521   BitVector TermRegs(NumRegs);
522   MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
523   if (TI != Preheader->end()) {
524     for (const MachineOperand &MO : TI->operands()) {
525       if (!MO.isReg())
526         continue;
527       unsigned Reg = MO.getReg();
528       if (!Reg)
529         continue;
530       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
531         TermRegs.set(*AI);
532     }
533   }
534 
535   // Now evaluate whether the potential candidates qualify.
536   // 1. Check if the candidate defined register is defined by another
537   //    instruction in the loop.
538   // 2. If the candidate is a load from stack slot (always true for now),
539   //    check if the slot is stored anywhere in the loop.
540   // 3. Make sure candidate def should not clobber
541   //    registers read by the terminator. Similarly its def should not be
542   //    clobbered by the terminator.
543   for (CandidateInfo &Candidate : Candidates) {
544     if (Candidate.FI != std::numeric_limits<int>::min() &&
545         StoredFIs.count(Candidate.FI))
546       continue;
547 
548     unsigned Def = Candidate.Def;
549     if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
550       bool Safe = true;
551       MachineInstr *MI = Candidate.MI;
552       for (const MachineOperand &MO : MI->operands()) {
553         if (!MO.isReg() || MO.isDef() || !MO.getReg())
554           continue;
555         unsigned Reg = MO.getReg();
556         if (PhysRegDefs.test(Reg) ||
557             PhysRegClobbers.test(Reg)) {
558           // If it's using a non-loop-invariant register, then it's obviously
559           // not safe to hoist.
560           Safe = false;
561           break;
562         }
563       }
564       if (Safe)
565         HoistPostRA(MI, Candidate.Def);
566     }
567   }
568 }
569 
570 /// Add register 'Reg' to the livein sets of BBs in the current loop, and make
571 /// sure it is not killed by any instructions in the loop.
572 void MachineLICMBase::AddToLiveIns(unsigned Reg) {
573   const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
574   for (MachineBasicBlock *BB : Blocks) {
575     if (!BB->isLiveIn(Reg))
576       BB->addLiveIn(Reg);
577     for (MachineInstr &MI : *BB) {
578       for (MachineOperand &MO : MI.operands()) {
579         if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
580         if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
581           MO.setIsKill(false);
582       }
583     }
584   }
585 }
586 
587 /// When an instruction is found to only use loop invariant operands that is
588 /// safe to hoist, this instruction is called to do the dirty work.
589 void MachineLICMBase::HoistPostRA(MachineInstr *MI, unsigned Def) {
590   MachineBasicBlock *Preheader = getCurPreheader();
591 
592   // Now move the instructions to the predecessor, inserting it before any
593   // terminator instructions.
594   DEBUG(dbgs() << "Hoisting to " << printMBBReference(*Preheader) << " from "
595                << printMBBReference(*MI->getParent()) << ": " << *MI);
596 
597   // Splice the instruction to the preheader.
598   MachineBasicBlock *MBB = MI->getParent();
599   Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
600 
601   // Add register to livein list to all the BBs in the current loop since a
602   // loop invariant must be kept live throughout the whole loop. This is
603   // important to ensure later passes do not scavenge the def register.
604   AddToLiveIns(Def);
605 
606   ++NumPostRAHoisted;
607   Changed = true;
608 }
609 
610 /// Check if this mbb is guaranteed to execute. If not then a load from this mbb
611 /// may not be safe to hoist.
612 bool MachineLICMBase::IsGuaranteedToExecute(MachineBasicBlock *BB) {
613   if (SpeculationState != SpeculateUnknown)
614     return SpeculationState == SpeculateFalse;
615 
616   if (BB != CurLoop->getHeader()) {
617     // Check loop exiting blocks.
618     SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
619     CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
620     for (MachineBasicBlock *CurrentLoopExitingBlock : CurrentLoopExitingBlocks)
621       if (!DT->dominates(BB, CurrentLoopExitingBlock)) {
622         SpeculationState = SpeculateTrue;
623         return false;
624       }
625   }
626 
627   SpeculationState = SpeculateFalse;
628   return true;
629 }
630 
631 void MachineLICMBase::EnterScope(MachineBasicBlock *MBB) {
632   DEBUG(dbgs() << "Entering " << printMBBReference(*MBB) << '\n');
633 
634   // Remember livein register pressure.
635   BackTrace.push_back(RegPressure);
636 }
637 
638 void MachineLICMBase::ExitScope(MachineBasicBlock *MBB) {
639   DEBUG(dbgs() << "Exiting " << printMBBReference(*MBB) << '\n');
640   BackTrace.pop_back();
641 }
642 
643 /// Destroy scope for the MBB that corresponds to the given dominator tree node
644 /// if its a leaf or all of its children are done. Walk up the dominator tree to
645 /// destroy ancestors which are now done.
646 void MachineLICMBase::ExitScopeIfDone(MachineDomTreeNode *Node,
647     DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
648     DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
649   if (OpenChildren[Node])
650     return;
651 
652   // Pop scope.
653   ExitScope(Node->getBlock());
654 
655   // Now traverse upwards to pop ancestors whose offsprings are all done.
656   while (MachineDomTreeNode *Parent = ParentMap[Node]) {
657     unsigned Left = --OpenChildren[Parent];
658     if (Left != 0)
659       break;
660     ExitScope(Parent->getBlock());
661     Node = Parent;
662   }
663 }
664 
665 /// Walk the specified loop in the CFG (defined by all blocks dominated by the
666 /// specified header block, and that are in the current loop) in depth first
667 /// order w.r.t the DominatorTree. This allows us to visit definitions before
668 /// uses, allowing us to hoist a loop body in one pass without iteration.
669 void MachineLICMBase::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
670   MachineBasicBlock *Preheader = getCurPreheader();
671   if (!Preheader)
672     return;
673 
674   SmallVector<MachineDomTreeNode*, 32> Scopes;
675   SmallVector<MachineDomTreeNode*, 8> WorkList;
676   DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
677   DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
678 
679   // Perform a DFS walk to determine the order of visit.
680   WorkList.push_back(HeaderN);
681   while (!WorkList.empty()) {
682     MachineDomTreeNode *Node = WorkList.pop_back_val();
683     assert(Node && "Null dominator tree node?");
684     MachineBasicBlock *BB = Node->getBlock();
685 
686     // If the header of the loop containing this basic block is a landing pad,
687     // then don't try to hoist instructions out of this loop.
688     const MachineLoop *ML = MLI->getLoopFor(BB);
689     if (ML && ML->getHeader()->isEHPad())
690       continue;
691 
692     // If this subregion is not in the top level loop at all, exit.
693     if (!CurLoop->contains(BB))
694       continue;
695 
696     Scopes.push_back(Node);
697     const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
698     unsigned NumChildren = Children.size();
699 
700     // Don't hoist things out of a large switch statement.  This often causes
701     // code to be hoisted that wasn't going to be executed, and increases
702     // register pressure in a situation where it's likely to matter.
703     if (BB->succ_size() >= 25)
704       NumChildren = 0;
705 
706     OpenChildren[Node] = NumChildren;
707     // Add children in reverse order as then the next popped worklist node is
708     // the first child of this node.  This means we ultimately traverse the
709     // DOM tree in exactly the same order as if we'd recursed.
710     for (int i = (int)NumChildren-1; i >= 0; --i) {
711       MachineDomTreeNode *Child = Children[i];
712       ParentMap[Child] = Node;
713       WorkList.push_back(Child);
714     }
715   }
716 
717   if (Scopes.size() == 0)
718     return;
719 
720   // Compute registers which are livein into the loop headers.
721   RegSeen.clear();
722   BackTrace.clear();
723   InitRegPressure(Preheader);
724 
725   // Now perform LICM.
726   for (MachineDomTreeNode *Node : Scopes) {
727     MachineBasicBlock *MBB = Node->getBlock();
728 
729     EnterScope(MBB);
730 
731     // Process the block
732     SpeculationState = SpeculateUnknown;
733     for (MachineBasicBlock::iterator
734          MII = MBB->begin(), E = MBB->end(); MII != E; ) {
735       MachineBasicBlock::iterator NextMII = MII; ++NextMII;
736       MachineInstr *MI = &*MII;
737       if (!Hoist(MI, Preheader))
738         UpdateRegPressure(MI);
739       // If we have hoisted an instruction that may store, it can only be a
740       // constant store.
741       MII = NextMII;
742     }
743 
744     // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
745     ExitScopeIfDone(Node, OpenChildren, ParentMap);
746   }
747 }
748 
749 /// Sink instructions into loops if profitable. This especially tries to prevent
750 /// register spills caused by register pressure if there is little to no
751 /// overhead moving instructions into loops.
752 void MachineLICMBase::SinkIntoLoop() {
753   MachineBasicBlock *Preheader = getCurPreheader();
754   if (!Preheader)
755     return;
756 
757   SmallVector<MachineInstr *, 8> Candidates;
758   for (MachineBasicBlock::instr_iterator I = Preheader->instr_begin();
759        I != Preheader->instr_end(); ++I) {
760     // We need to ensure that we can safely move this instruction into the loop.
761     // As such, it must not have side-effects, e.g. such as a call has.
762     if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(&*I))
763       Candidates.push_back(&*I);
764   }
765 
766   for (MachineInstr *I : Candidates) {
767     const MachineOperand &MO = I->getOperand(0);
768     if (!MO.isDef() || !MO.isReg() || !MO.getReg())
769       continue;
770     if (!MRI->hasOneDef(MO.getReg()))
771       continue;
772     bool CanSink = true;
773     MachineBasicBlock *B = nullptr;
774     for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
775       // FIXME: Come up with a proper cost model that estimates whether sinking
776       // the instruction (and thus possibly executing it on every loop
777       // iteration) is more expensive than a register.
778       // For now assumes that copies are cheap and thus almost always worth it.
779       if (!MI.isCopy()) {
780         CanSink = false;
781         break;
782       }
783       if (!B) {
784         B = MI.getParent();
785         continue;
786       }
787       B = DT->findNearestCommonDominator(B, MI.getParent());
788       if (!B) {
789         CanSink = false;
790         break;
791       }
792     }
793     if (!CanSink || !B || B == Preheader)
794       continue;
795     B->splice(B->getFirstNonPHI(), Preheader, I);
796   }
797 }
798 
799 static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
800   return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
801 }
802 
803 /// Find all virtual register references that are liveout of the preheader to
804 /// initialize the starting "register pressure". Note this does not count live
805 /// through (livein but not used) registers.
806 void MachineLICMBase::InitRegPressure(MachineBasicBlock *BB) {
807   std::fill(RegPressure.begin(), RegPressure.end(), 0);
808 
809   // If the preheader has only a single predecessor and it ends with a
810   // fallthrough or an unconditional branch, then scan its predecessor for live
811   // defs as well. This happens whenever the preheader is created by splitting
812   // the critical edge from the loop predecessor to the loop header.
813   if (BB->pred_size() == 1) {
814     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
815     SmallVector<MachineOperand, 4> Cond;
816     if (!TII->analyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
817       InitRegPressure(*BB->pred_begin());
818   }
819 
820   for (const MachineInstr &MI : *BB)
821     UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
822 }
823 
824 /// Update estimate of register pressure after the specified instruction.
825 void MachineLICMBase::UpdateRegPressure(const MachineInstr *MI,
826                                         bool ConsiderUnseenAsDef) {
827   auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
828   for (const auto &RPIdAndCost : Cost) {
829     unsigned Class = RPIdAndCost.first;
830     if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second)
831       RegPressure[Class] = 0;
832     else
833       RegPressure[Class] += RPIdAndCost.second;
834   }
835 }
836 
837 /// Calculate the additional register pressure that the registers used in MI
838 /// cause.
839 ///
840 /// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
841 /// figure out which usages are live-ins.
842 /// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
843 DenseMap<unsigned, int>
844 MachineLICMBase::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
845                                   bool ConsiderUnseenAsDef) {
846   DenseMap<unsigned, int> Cost;
847   if (MI->isImplicitDef())
848     return Cost;
849   for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
850     const MachineOperand &MO = MI->getOperand(i);
851     if (!MO.isReg() || MO.isImplicit())
852       continue;
853     unsigned Reg = MO.getReg();
854     if (!TargetRegisterInfo::isVirtualRegister(Reg))
855       continue;
856 
857     // FIXME: It seems bad to use RegSeen only for some of these calculations.
858     bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
859     const TargetRegisterClass *RC = MRI->getRegClass(Reg);
860 
861     RegClassWeight W = TRI->getRegClassWeight(RC);
862     int RCCost = 0;
863     if (MO.isDef())
864       RCCost = W.RegWeight;
865     else {
866       bool isKill = isOperandKill(MO, MRI);
867       if (isNew && !isKill && ConsiderUnseenAsDef)
868         // Haven't seen this, it must be a livein.
869         RCCost = W.RegWeight;
870       else if (!isNew && isKill)
871         RCCost = -W.RegWeight;
872     }
873     if (RCCost == 0)
874       continue;
875     const int *PS = TRI->getRegClassPressureSets(RC);
876     for (; *PS != -1; ++PS) {
877       if (Cost.find(*PS) == Cost.end())
878         Cost[*PS] = RCCost;
879       else
880         Cost[*PS] += RCCost;
881     }
882   }
883   return Cost;
884 }
885 
886 /// Return true if this machine instruction loads from global offset table or
887 /// constant pool.
888 static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
889   assert(MI.mayLoad() && "Expected MI that loads!");
890 
891   // If we lost memory operands, conservatively assume that the instruction
892   // reads from everything..
893   if (MI.memoperands_empty())
894     return true;
895 
896   for (MachineMemOperand *MemOp : MI.memoperands())
897     if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
898       if (PSV->isGOT() || PSV->isConstantPool())
899         return true;
900 
901   return false;
902 }
903 
904 // This function iterates through all the operands of the input store MI and
905 // checks that each register operand statisfies isCallerPreservedPhysReg.
906 // This means, the value being stored and the address where it is being stored
907 // is constant throughout the body of the function (not including prologue and
908 // epilogue). When called with an MI that isn't a store, it returns false.
909 // A future improvement can be to check if the store registers are constant
910 // throughout the loop rather than throughout the funtion.
911 static bool isInvariantStore(const MachineInstr &MI,
912                              const TargetRegisterInfo *TRI,
913                              const MachineRegisterInfo *MRI) {
914 
915   bool FoundCallerPresReg = false;
916   if (!MI.mayStore() || MI.hasUnmodeledSideEffects() ||
917       (MI.getNumOperands() == 0))
918     return false;
919 
920   // Check that all register operands are caller-preserved physical registers.
921   for (const MachineOperand &MO : MI.operands()) {
922     if (MO.isReg()) {
923       unsigned Reg = MO.getReg();
924       // If operand is a virtual register, check if it comes from a copy of a
925       // physical register.
926       if (TargetRegisterInfo::isVirtualRegister(Reg))
927         Reg = TRI->lookThruCopyLike(MO.getReg(), MRI);
928       if (TargetRegisterInfo::isVirtualRegister(Reg))
929         return false;
930       if (!TRI->isCallerPreservedPhysReg(Reg, *MI.getMF()))
931         return false;
932       else
933         FoundCallerPresReg = true;
934     } else if (!MO.isImm()) {
935         return false;
936     }
937   }
938   return FoundCallerPresReg;
939 }
940 
941 // Return true if the input MI is a copy instruction that feeds an invariant
942 // store instruction. This means that the src of the copy has to satisfy
943 // isCallerPreservedPhysReg and atleast one of it's users should satisfy
944 // isInvariantStore.
945 static bool isCopyFeedingInvariantStore(const MachineInstr &MI,
946                                         const MachineRegisterInfo *MRI,
947                                         const TargetRegisterInfo *TRI) {
948 
949   // FIXME: If targets would like to look through instructions that aren't
950   // pure copies, this can be updated to a query.
951   if (!MI.isCopy())
952     return false;
953 
954   const MachineFunction *MF = MI.getMF();
955   // Check that we are copying a constant physical register.
956   unsigned CopySrcReg = MI.getOperand(1).getReg();
957   if (TargetRegisterInfo::isVirtualRegister(CopySrcReg))
958     return false;
959 
960   if (!TRI->isCallerPreservedPhysReg(CopySrcReg, *MF))
961     return false;
962 
963   unsigned CopyDstReg = MI.getOperand(0).getReg();
964   // Check if any of the uses of the copy are invariant stores.
965   assert (TargetRegisterInfo::isVirtualRegister(CopyDstReg) &&
966           "copy dst is not a virtual reg");
967 
968   for (MachineInstr &UseMI : MRI->use_instructions(CopyDstReg)) {
969     if (UseMI.mayStore() && isInvariantStore(UseMI, TRI, MRI))
970       return true;
971   }
972   return false;
973 }
974 
975 /// Returns true if the instruction may be a suitable candidate for LICM.
976 /// e.g. If the instruction is a call, then it's obviously not safe to hoist it.
977 bool MachineLICMBase::IsLICMCandidate(MachineInstr &I) {
978   // Check if it's safe to move the instruction.
979   bool DontMoveAcrossStore = true;
980   if ((!I.isSafeToMove(AA, DontMoveAcrossStore)) &&
981       !(HoistConstStores && isInvariantStore(I, TRI, MRI))) {
982     return false;
983   }
984 
985   // If it is load then check if it is guaranteed to execute by making sure that
986   // it dominates all exiting blocks. If it doesn't, then there is a path out of
987   // the loop which does not execute this load, so we can't hoist it. Loads
988   // from constant memory are not safe to speculate all the time, for example
989   // indexed load from a jump table.
990   // Stores and side effects are already checked by isSafeToMove.
991   if (I.mayLoad() && !mayLoadFromGOTOrConstantPool(I) &&
992       !IsGuaranteedToExecute(I.getParent()))
993     return false;
994 
995   return true;
996 }
997 
998 /// Returns true if the instruction is loop invariant.
999 /// I.e., all virtual register operands are defined outside of the loop,
1000 /// physical registers aren't accessed explicitly, and there are no side
1001 /// effects that aren't captured by the operands or other flags.
1002 bool MachineLICMBase::IsLoopInvariantInst(MachineInstr &I) {
1003   if (!IsLICMCandidate(I))
1004     return false;
1005 
1006   // The instruction is loop invariant if all of its operands are.
1007   for (const MachineOperand &MO : I.operands()) {
1008     if (!MO.isReg())
1009       continue;
1010 
1011     unsigned Reg = MO.getReg();
1012     if (Reg == 0) continue;
1013 
1014     // Don't hoist an instruction that uses or defines a physical register.
1015     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1016       if (MO.isUse()) {
1017         // If the physreg has no defs anywhere, it's just an ambient register
1018         // and we can freely move its uses. Alternatively, if it's allocatable,
1019         // it could get allocated to something with a def during allocation.
1020         // However, if the physreg is known to always be caller saved/restored
1021         // then this use is safe to hoist.
1022         if (!MRI->isConstantPhysReg(Reg) &&
1023             !(TRI->isCallerPreservedPhysReg(Reg, *I.getMF())))
1024           return false;
1025         // Otherwise it's safe to move.
1026         continue;
1027       } else if (!MO.isDead()) {
1028         // A def that isn't dead. We can't move it.
1029         return false;
1030       } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
1031         // If the reg is live into the loop, we can't hoist an instruction
1032         // which would clobber it.
1033         return false;
1034       }
1035     }
1036 
1037     if (!MO.isUse())
1038       continue;
1039 
1040     assert(MRI->getVRegDef(Reg) &&
1041            "Machine instr not mapped for this vreg?!");
1042 
1043     // If the loop contains the definition of an operand, then the instruction
1044     // isn't loop invariant.
1045     if (CurLoop->contains(MRI->getVRegDef(Reg)))
1046       return false;
1047   }
1048 
1049   // If we got this far, the instruction is loop invariant!
1050   return true;
1051 }
1052 
1053 /// Return true if the specified instruction is used by a phi node and hoisting
1054 /// it could cause a copy to be inserted.
1055 bool MachineLICMBase::HasLoopPHIUse(const MachineInstr *MI) const {
1056   SmallVector<const MachineInstr*, 8> Work(1, MI);
1057   do {
1058     MI = Work.pop_back_val();
1059     for (const MachineOperand &MO : MI->operands()) {
1060       if (!MO.isReg() || !MO.isDef())
1061         continue;
1062       unsigned Reg = MO.getReg();
1063       if (!TargetRegisterInfo::isVirtualRegister(Reg))
1064         continue;
1065       for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
1066         // A PHI may cause a copy to be inserted.
1067         if (UseMI.isPHI()) {
1068           // A PHI inside the loop causes a copy because the live range of Reg is
1069           // extended across the PHI.
1070           if (CurLoop->contains(&UseMI))
1071             return true;
1072           // A PHI in an exit block can cause a copy to be inserted if the PHI
1073           // has multiple predecessors in the loop with different values.
1074           // For now, approximate by rejecting all exit blocks.
1075           if (isExitBlock(UseMI.getParent()))
1076             return true;
1077           continue;
1078         }
1079         // Look past copies as well.
1080         if (UseMI.isCopy() && CurLoop->contains(&UseMI))
1081           Work.push_back(&UseMI);
1082       }
1083     }
1084   } while (!Work.empty());
1085   return false;
1086 }
1087 
1088 /// Compute operand latency between a def of 'Reg' and an use in the current
1089 /// loop, return true if the target considered it high.
1090 bool MachineLICMBase::HasHighOperandLatency(MachineInstr &MI,
1091                                             unsigned DefIdx,
1092                                             unsigned Reg) const {
1093   if (MRI->use_nodbg_empty(Reg))
1094     return false;
1095 
1096   for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
1097     if (UseMI.isCopyLike())
1098       continue;
1099     if (!CurLoop->contains(UseMI.getParent()))
1100       continue;
1101     for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
1102       const MachineOperand &MO = UseMI.getOperand(i);
1103       if (!MO.isReg() || !MO.isUse())
1104         continue;
1105       unsigned MOReg = MO.getReg();
1106       if (MOReg != Reg)
1107         continue;
1108 
1109       if (TII->hasHighOperandLatency(SchedModel, MRI, MI, DefIdx, UseMI, i))
1110         return true;
1111     }
1112 
1113     // Only look at the first in loop use.
1114     break;
1115   }
1116 
1117   return false;
1118 }
1119 
1120 /// Return true if the instruction is marked "cheap" or the operand latency
1121 /// between its def and a use is one or less.
1122 bool MachineLICMBase::IsCheapInstruction(MachineInstr &MI) const {
1123   if (TII->isAsCheapAsAMove(MI) || MI.isCopyLike())
1124     return true;
1125 
1126   bool isCheap = false;
1127   unsigned NumDefs = MI.getDesc().getNumDefs();
1128   for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1129     MachineOperand &DefMO = MI.getOperand(i);
1130     if (!DefMO.isReg() || !DefMO.isDef())
1131       continue;
1132     --NumDefs;
1133     unsigned Reg = DefMO.getReg();
1134     if (TargetRegisterInfo::isPhysicalRegister(Reg))
1135       continue;
1136 
1137     if (!TII->hasLowDefLatency(SchedModel, MI, i))
1138       return false;
1139     isCheap = true;
1140   }
1141 
1142   return isCheap;
1143 }
1144 
1145 /// Visit BBs from header to current BB, check if hoisting an instruction of the
1146 /// given cost matrix can cause high register pressure.
1147 bool
1148 MachineLICMBase::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
1149                                          bool CheapInstr) {
1150   for (const auto &RPIdAndCost : Cost) {
1151     if (RPIdAndCost.second <= 0)
1152       continue;
1153 
1154     unsigned Class = RPIdAndCost.first;
1155     int Limit = RegLimit[Class];
1156 
1157     // Don't hoist cheap instructions if they would increase register pressure,
1158     // even if we're under the limit.
1159     if (CheapInstr && !HoistCheapInsts)
1160       return true;
1161 
1162     for (const auto &RP : BackTrace)
1163       if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit)
1164         return true;
1165   }
1166 
1167   return false;
1168 }
1169 
1170 /// Traverse the back trace from header to the current block and update their
1171 /// register pressures to reflect the effect of hoisting MI from the current
1172 /// block to the preheader.
1173 void MachineLICMBase::UpdateBackTraceRegPressure(const MachineInstr *MI) {
1174   // First compute the 'cost' of the instruction, i.e. its contribution
1175   // to register pressure.
1176   auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
1177                                /*ConsiderUnseenAsDef=*/false);
1178 
1179   // Update register pressure of blocks from loop header to current block.
1180   for (auto &RP : BackTrace)
1181     for (const auto &RPIdAndCost : Cost)
1182       RP[RPIdAndCost.first] += RPIdAndCost.second;
1183 }
1184 
1185 /// Return true if it is potentially profitable to hoist the given loop
1186 /// invariant.
1187 bool MachineLICMBase::IsProfitableToHoist(MachineInstr &MI) {
1188   if (MI.isImplicitDef())
1189     return true;
1190 
1191   // Besides removing computation from the loop, hoisting an instruction has
1192   // these effects:
1193   //
1194   // - The value defined by the instruction becomes live across the entire
1195   //   loop. This increases register pressure in the loop.
1196   //
1197   // - If the value is used by a PHI in the loop, a copy will be required for
1198   //   lowering the PHI after extending the live range.
1199   //
1200   // - When hoisting the last use of a value in the loop, that value no longer
1201   //   needs to be live in the loop. This lowers register pressure in the loop.
1202 
1203   if (HoistConstStores &&  isCopyFeedingInvariantStore(MI, MRI, TRI))
1204     return true;
1205 
1206   bool CheapInstr = IsCheapInstruction(MI);
1207   bool CreatesCopy = HasLoopPHIUse(&MI);
1208 
1209   // Don't hoist a cheap instruction if it would create a copy in the loop.
1210   if (CheapInstr && CreatesCopy) {
1211     DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1212     return false;
1213   }
1214 
1215   // Rematerializable instructions should always be hoisted since the register
1216   // allocator can just pull them down again when needed.
1217   if (TII->isTriviallyReMaterializable(MI, AA))
1218     return true;
1219 
1220   // FIXME: If there are long latency loop-invariant instructions inside the
1221   // loop at this point, why didn't the optimizer's LICM hoist them?
1222   for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1223     const MachineOperand &MO = MI.getOperand(i);
1224     if (!MO.isReg() || MO.isImplicit())
1225       continue;
1226     unsigned Reg = MO.getReg();
1227     if (!TargetRegisterInfo::isVirtualRegister(Reg))
1228       continue;
1229     if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) {
1230       DEBUG(dbgs() << "Hoist High Latency: " << MI);
1231       ++NumHighLatency;
1232       return true;
1233     }
1234   }
1235 
1236   // Estimate register pressure to determine whether to LICM the instruction.
1237   // In low register pressure situation, we can be more aggressive about
1238   // hoisting. Also, favors hoisting long latency instructions even in
1239   // moderately high pressure situation.
1240   // Cheap instructions will only be hoisted if they don't increase register
1241   // pressure at all.
1242   auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
1243                                /*ConsiderUnseenAsDef=*/false);
1244 
1245   // Visit BBs from header to current BB, if hoisting this doesn't cause
1246   // high register pressure, then it's safe to proceed.
1247   if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1248     DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1249     ++NumLowRP;
1250     return true;
1251   }
1252 
1253   // Don't risk increasing register pressure if it would create copies.
1254   if (CreatesCopy) {
1255     DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
1256     return false;
1257   }
1258 
1259   // Do not "speculate" in high register pressure situation. If an
1260   // instruction is not guaranteed to be executed in the loop, it's best to be
1261   // conservative.
1262   if (AvoidSpeculation &&
1263       (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
1264     DEBUG(dbgs() << "Won't speculate: " << MI);
1265     return false;
1266   }
1267 
1268   // High register pressure situation, only hoist if the instruction is going
1269   // to be remat'ed.
1270   if (!TII->isTriviallyReMaterializable(MI, AA) &&
1271       !MI.isDereferenceableInvariantLoad(AA)) {
1272     DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1273     return false;
1274   }
1275 
1276   return true;
1277 }
1278 
1279 /// Unfold a load from the given machineinstr if the load itself could be
1280 /// hoisted. Return the unfolded and hoistable load, or null if the load
1281 /// couldn't be unfolded or if it wouldn't be hoistable.
1282 MachineInstr *MachineLICMBase::ExtractHoistableLoad(MachineInstr *MI) {
1283   // Don't unfold simple loads.
1284   if (MI->canFoldAsLoad())
1285     return nullptr;
1286 
1287   // If not, we may be able to unfold a load and hoist that.
1288   // First test whether the instruction is loading from an amenable
1289   // memory location.
1290   if (!MI->isDereferenceableInvariantLoad(AA))
1291     return nullptr;
1292 
1293   // Next determine the register class for a temporary register.
1294   unsigned LoadRegIndex;
1295   unsigned NewOpc =
1296     TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1297                                     /*UnfoldLoad=*/true,
1298                                     /*UnfoldStore=*/false,
1299                                     &LoadRegIndex);
1300   if (NewOpc == 0) return nullptr;
1301   const MCInstrDesc &MID = TII->get(NewOpc);
1302   MachineFunction &MF = *MI->getMF();
1303   const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
1304   // Ok, we're unfolding. Create a temporary register and do the unfold.
1305   unsigned Reg = MRI->createVirtualRegister(RC);
1306 
1307   SmallVector<MachineInstr *, 2> NewMIs;
1308   bool Success = TII->unfoldMemoryOperand(MF, *MI, Reg,
1309                                           /*UnfoldLoad=*/true,
1310                                           /*UnfoldStore=*/false, NewMIs);
1311   (void)Success;
1312   assert(Success &&
1313          "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1314          "succeeded!");
1315   assert(NewMIs.size() == 2 &&
1316          "Unfolded a load into multiple instructions!");
1317   MachineBasicBlock *MBB = MI->getParent();
1318   MachineBasicBlock::iterator Pos = MI;
1319   MBB->insert(Pos, NewMIs[0]);
1320   MBB->insert(Pos, NewMIs[1]);
1321   // If unfolding produced a load that wasn't loop-invariant or profitable to
1322   // hoist, discard the new instructions and bail.
1323   if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
1324     NewMIs[0]->eraseFromParent();
1325     NewMIs[1]->eraseFromParent();
1326     return nullptr;
1327   }
1328 
1329   // Update register pressure for the unfolded instruction.
1330   UpdateRegPressure(NewMIs[1]);
1331 
1332   // Otherwise we successfully unfolded a load that we can hoist.
1333   MI->eraseFromParent();
1334   return NewMIs[0];
1335 }
1336 
1337 /// Initialize the CSE map with instructions that are in the current loop
1338 /// preheader that may become duplicates of instructions that are hoisted
1339 /// out of the loop.
1340 void MachineLICMBase::InitCSEMap(MachineBasicBlock *BB) {
1341   for (MachineInstr &MI : *BB)
1342     CSEMap[MI.getOpcode()].push_back(&MI);
1343 }
1344 
1345 /// Find an instruction amount PrevMIs that is a duplicate of MI.
1346 /// Return this instruction if it's found.
1347 const MachineInstr*
1348 MachineLICMBase::LookForDuplicate(const MachineInstr *MI,
1349                                   std::vector<const MachineInstr*> &PrevMIs) {
1350   for (const MachineInstr *PrevMI : PrevMIs)
1351     if (TII->produceSameValue(*MI, *PrevMI, (PreRegAlloc ? MRI : nullptr)))
1352       return PrevMI;
1353 
1354   return nullptr;
1355 }
1356 
1357 /// Given a LICM'ed instruction, look for an instruction on the preheader that
1358 /// computes the same value. If it's found, do a RAU on with the definition of
1359 /// the existing instruction rather than hoisting the instruction to the
1360 /// preheader.
1361 bool MachineLICMBase::EliminateCSE(MachineInstr *MI,
1362     DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI) {
1363   // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1364   // the undef property onto uses.
1365   if (CI == CSEMap.end() || MI->isImplicitDef())
1366     return false;
1367 
1368   if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
1369     DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
1370 
1371     // Replace virtual registers defined by MI by their counterparts defined
1372     // by Dup.
1373     SmallVector<unsigned, 2> Defs;
1374     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1375       const MachineOperand &MO = MI->getOperand(i);
1376 
1377       // Physical registers may not differ here.
1378       assert((!MO.isReg() || MO.getReg() == 0 ||
1379               !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1380               MO.getReg() == Dup->getOperand(i).getReg()) &&
1381              "Instructions with different phys regs are not identical!");
1382 
1383       if (MO.isReg() && MO.isDef() &&
1384           !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1385         Defs.push_back(i);
1386     }
1387 
1388     SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1389     for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1390       unsigned Idx = Defs[i];
1391       unsigned Reg = MI->getOperand(Idx).getReg();
1392       unsigned DupReg = Dup->getOperand(Idx).getReg();
1393       OrigRCs.push_back(MRI->getRegClass(DupReg));
1394 
1395       if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1396         // Restore old RCs if more than one defs.
1397         for (unsigned j = 0; j != i; ++j)
1398           MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1399         return false;
1400       }
1401     }
1402 
1403     for (unsigned Idx : Defs) {
1404       unsigned Reg = MI->getOperand(Idx).getReg();
1405       unsigned DupReg = Dup->getOperand(Idx).getReg();
1406       MRI->replaceRegWith(Reg, DupReg);
1407       MRI->clearKillFlags(DupReg);
1408     }
1409 
1410     MI->eraseFromParent();
1411     ++NumCSEed;
1412     return true;
1413   }
1414   return false;
1415 }
1416 
1417 /// Return true if the given instruction will be CSE'd if it's hoisted out of
1418 /// the loop.
1419 bool MachineLICMBase::MayCSE(MachineInstr *MI) {
1420   unsigned Opcode = MI->getOpcode();
1421   DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator
1422     CI = CSEMap.find(Opcode);
1423   // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1424   // the undef property onto uses.
1425   if (CI == CSEMap.end() || MI->isImplicitDef())
1426     return false;
1427 
1428   return LookForDuplicate(MI, CI->second) != nullptr;
1429 }
1430 
1431 /// When an instruction is found to use only loop invariant operands
1432 /// that are safe to hoist, this instruction is called to do the dirty work.
1433 /// It returns true if the instruction is hoisted.
1434 bool MachineLICMBase::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
1435   // First check whether we should hoist this instruction.
1436   if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
1437     // If not, try unfolding a hoistable load.
1438     MI = ExtractHoistableLoad(MI);
1439     if (!MI) return false;
1440   }
1441 
1442   // If we have hoisted an instruction that may store, it can only be a constant
1443   // store.
1444   if (MI->mayStore())
1445     NumStoreConst++;
1446 
1447   // Now move the instructions to the predecessor, inserting it before any
1448   // terminator instructions.
1449   DEBUG({
1450       dbgs() << "Hoisting " << *MI;
1451       if (MI->getParent()->getBasicBlock())
1452         dbgs() << " from " << printMBBReference(*MI->getParent());
1453       if (Preheader->getBasicBlock())
1454         dbgs() << " to " << printMBBReference(*Preheader);
1455       dbgs() << "\n";
1456     });
1457 
1458   // If this is the first instruction being hoisted to the preheader,
1459   // initialize the CSE map with potential common expressions.
1460   if (FirstInLoop) {
1461     InitCSEMap(Preheader);
1462     FirstInLoop = false;
1463   }
1464 
1465   // Look for opportunity to CSE the hoisted instruction.
1466   unsigned Opcode = MI->getOpcode();
1467   DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator
1468     CI = CSEMap.find(Opcode);
1469   if (!EliminateCSE(MI, CI)) {
1470     // Otherwise, splice the instruction to the preheader.
1471     Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
1472 
1473     // Since we are moving the instruction out of its basic block, we do not
1474     // retain its debug location. Doing so would degrade the debugging
1475     // experience and adversely affect the accuracy of profiling information.
1476     MI->setDebugLoc(DebugLoc());
1477 
1478     // Update register pressure for BBs from header to this block.
1479     UpdateBackTraceRegPressure(MI);
1480 
1481     // Clear the kill flags of any register this instruction defines,
1482     // since they may need to be live throughout the entire loop
1483     // rather than just live for part of it.
1484     for (MachineOperand &MO : MI->operands())
1485       if (MO.isReg() && MO.isDef() && !MO.isDead())
1486         MRI->clearKillFlags(MO.getReg());
1487 
1488     // Add to the CSE map.
1489     if (CI != CSEMap.end())
1490       CI->second.push_back(MI);
1491     else
1492       CSEMap[Opcode].push_back(MI);
1493   }
1494 
1495   ++NumHoisted;
1496   Changed = true;
1497 
1498   return true;
1499 }
1500 
1501 /// Get the preheader for the current loop, splitting a critical edge if needed.
1502 MachineBasicBlock *MachineLICMBase::getCurPreheader() {
1503   // Determine the block to which to hoist instructions. If we can't find a
1504   // suitable loop predecessor, we can't do any hoisting.
1505 
1506   // If we've tried to get a preheader and failed, don't try again.
1507   if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1508     return nullptr;
1509 
1510   if (!CurPreheader) {
1511     CurPreheader = CurLoop->getLoopPreheader();
1512     if (!CurPreheader) {
1513       MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1514       if (!Pred) {
1515         CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1516         return nullptr;
1517       }
1518 
1519       CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), *this);
1520       if (!CurPreheader) {
1521         CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1522         return nullptr;
1523       }
1524     }
1525   }
1526   return CurPreheader;
1527 }
1528