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