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