a55b3e652d9b67603f0f8a49a1e75e9453f6032e
[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 #define DEBUG_TYPE "machine-licm"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineLoopInfo.h"
28 #include "llvm/CodeGen/MachineMemOperand.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/PseudoSourceValue.h"
31 #include "llvm/Target/TargetLowering.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Target/TargetInstrItineraries.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/ADT/DenseMap.h"
38 #include "llvm/ADT/SmallSet.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/raw_ostream.h"
43
44 using namespace llvm;
45
46 static cl::opt<bool>
47 TrackRegPressure("rp-aware-machine-licm",
48                  cl::desc("Register pressure aware machine LICM"),
49                  cl::init(false), cl::Hidden);
50
51 STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
52 STATISTIC(NumCSEed,   "Number of hoisted machine instructions CSEed");
53 STATISTIC(NumPostRAHoisted,
54           "Number of machine instructions hoisted out of loops post regalloc");
55
56 namespace {
57   class MachineLICM : public MachineFunctionPass {
58     bool PreRegAlloc;
59
60     const TargetMachine   *TM;
61     const TargetInstrInfo *TII;
62     const TargetLowering *TLI;
63     const TargetRegisterInfo *TRI;
64     const MachineFrameInfo *MFI;
65     MachineRegisterInfo *MRI;
66     const InstrItineraryData *InstrItins;
67
68     // Various analyses that we use...
69     AliasAnalysis        *AA;      // Alias analysis info.
70     MachineLoopInfo      *MLI;     // Current MachineLoopInfo
71     MachineDominatorTree *DT;      // Machine dominator tree for the cur loop
72
73     // State that is updated as we process loops
74     bool         Changed;          // True if a loop is changed.
75     bool         FirstInLoop;      // True if it's the first LICM in the loop.
76     MachineLoop *CurLoop;          // The current loop we are working on.
77     MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
78
79     BitVector AllocatableSet;
80
81     // Track 'estimated' register pressure.
82     SmallVector<unsigned, 8> RegPressure;
83     SmallVector<unsigned, 8> RegLimit;
84
85     // For each opcode, keep a list of potential CSE instructions.
86     DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
87
88   public:
89     static char ID; // Pass identification, replacement for typeid
90     MachineLICM() :
91       MachineFunctionPass(ID), PreRegAlloc(true) {}
92
93     explicit MachineLICM(bool PreRA) :
94       MachineFunctionPass(ID), PreRegAlloc(PreRA) {}
95
96     virtual bool runOnMachineFunction(MachineFunction &MF);
97
98     const char *getPassName() const { return "Machine Instruction LICM"; }
99
100     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
101       AU.setPreservesCFG();
102       AU.addRequired<MachineLoopInfo>();
103       AU.addRequired<MachineDominatorTree>();
104       AU.addRequired<AliasAnalysis>();
105       AU.addPreserved<MachineLoopInfo>();
106       AU.addPreserved<MachineDominatorTree>();
107       MachineFunctionPass::getAnalysisUsage(AU);
108     }
109
110     virtual void releaseMemory() {
111       RegPressure.clear();
112       RegLimit.clear();
113       CSEMap.clear();
114     }
115
116   private:
117     /// CandidateInfo - Keep track of information about hoisting candidates.
118     struct CandidateInfo {
119       MachineInstr *MI;
120       unsigned      Def;
121       int           FI;
122       CandidateInfo(MachineInstr *mi, unsigned def, int fi)
123         : MI(mi), Def(def), FI(fi) {}
124     };
125
126     /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
127     /// invariants out to the preheader.
128     void HoistRegionPostRA();
129
130     /// HoistPostRA - When an instruction is found to only use loop invariant
131     /// operands that is safe to hoist, this instruction is called to do the
132     /// dirty work.
133     void HoistPostRA(MachineInstr *MI, unsigned Def);
134
135     /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
136     /// gather register def and frame object update information.
137     void ProcessMI(MachineInstr *MI, unsigned *PhysRegDefs,
138                    SmallSet<int, 32> &StoredFIs,
139                    SmallVector<CandidateInfo, 32> &Candidates);
140
141     /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
142     /// current loop.
143     void AddToLiveIns(unsigned Reg);
144
145     /// IsLICMCandidate - Returns true if the instruction may be a suitable
146     /// candidate for LICM. e.g. If the instruction is a call, then it's
147     /// obviously not safe to hoist it.
148     bool IsLICMCandidate(MachineInstr &I);
149
150     /// IsLoopInvariantInst - Returns true if the instruction is loop
151     /// invariant. I.e., all virtual register operands are defined outside of
152     /// the loop, physical registers aren't accessed (explicitly or implicitly),
153     /// and the instruction is hoistable.
154     /// 
155     bool IsLoopInvariantInst(MachineInstr &I);
156
157     /// ComputeOperandLatency - Compute operand latency between a def of 'Reg'
158     /// and an use in the current loop.
159     int ComputeOperandLatency(MachineInstr &MI, unsigned DefIdx, unsigned Reg);
160
161     /// IsProfitableToHoist - Return true if it is potentially profitable to
162     /// hoist the given loop invariant.
163     bool IsProfitableToHoist(MachineInstr &MI);
164
165     /// HoistRegion - Walk the specified region of the CFG (defined by all
166     /// blocks dominated by the specified block, and that are in the current
167     /// loop) in depth first order w.r.t the DominatorTree. This allows us to
168     /// visit definitions before uses, allowing us to hoist a loop body in one
169     /// pass without iteration.
170     ///
171     void HoistRegion(MachineDomTreeNode *N);
172
173     /// InitRegPressure - Find all virtual register references that are livein
174     /// to the block to initialize the starting "register pressure". Note this
175     /// does not count live through (livein but not used) registers.
176     void InitRegPressure(MachineBasicBlock *BB);
177
178     /// UpdateRegPressureBefore / UpdateRegPressureAfter - Update estimate of
179     /// register pressure before and after executing a specifi instruction.
180     void UpdateRegPressureBefore(const MachineInstr *MI);
181     void UpdateRegPressureAfter(const MachineInstr *MI);
182
183     /// isLoadFromConstantMemory - Return true if the given instruction is a
184     /// load from constant memory.
185     bool isLoadFromConstantMemory(MachineInstr *MI);
186
187     /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
188     /// the load itself could be hoisted. Return the unfolded and hoistable
189     /// load, or null if the load couldn't be unfolded or if it wouldn't
190     /// be hoistable.
191     MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
192
193     /// LookForDuplicate - Find an instruction amount PrevMIs that is a
194     /// duplicate of MI. Return this instruction if it's found.
195     const MachineInstr *LookForDuplicate(const MachineInstr *MI,
196                                      std::vector<const MachineInstr*> &PrevMIs);
197
198     /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
199     /// the preheader that compute the same value. If it's found, do a RAU on
200     /// with the definition of the existing instruction rather than hoisting
201     /// the instruction to the preheader.
202     bool EliminateCSE(MachineInstr *MI,
203            DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
204
205     /// Hoist - When an instruction is found to only use loop invariant operands
206     /// that is safe to hoist, this instruction is called to do the dirty work.
207     ///
208     void Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
209
210     /// InitCSEMap - Initialize the CSE map with instructions that are in the
211     /// current loop preheader that may become duplicates of instructions that
212     /// are hoisted out of the loop.
213     void InitCSEMap(MachineBasicBlock *BB);
214
215     /// getCurPreheader - Get the preheader for the current loop, splitting
216     /// a critical edge if needed.
217     MachineBasicBlock *getCurPreheader();
218   };
219 } // end anonymous namespace
220
221 char MachineLICM::ID = 0;
222 INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
223                 "Machine Loop Invariant Code Motion", false, false)
224 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
225 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
226 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
227 INITIALIZE_PASS_END(MachineLICM, "machinelicm",
228                 "Machine Loop Invariant Code Motion", false, false)
229
230 FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
231   return new MachineLICM(PreRegAlloc);
232 }
233
234 /// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
235 /// loop that has a unique predecessor.
236 static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
237   // Check whether this loop even has a unique predecessor.
238   if (!CurLoop->getLoopPredecessor())
239     return false;
240   // Ok, now check to see if any of its outer loops do.
241   for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
242     if (L->getLoopPredecessor())
243       return false;
244   // None of them did, so this is the outermost with a unique predecessor.
245   return true;
246 }
247
248 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
249   if (PreRegAlloc)
250     DEBUG(dbgs() << "******** Pre-regalloc Machine LICM ********\n");
251   else
252     DEBUG(dbgs() << "******** Post-regalloc Machine LICM ********\n");
253
254   Changed = FirstInLoop = false;
255   TM = &MF.getTarget();
256   TII = TM->getInstrInfo();
257   TLI = TM->getTargetLowering();
258   TRI = TM->getRegisterInfo();
259   MFI = MF.getFrameInfo();
260   MRI = &MF.getRegInfo();
261   InstrItins = TM->getInstrItineraryData();
262   AllocatableSet = TRI->getAllocatableSet(MF);
263
264   if (PreRegAlloc) {
265     // Estimate register pressure during pre-regalloc pass.
266     unsigned NumRC = TRI->getNumRegClasses();
267     RegPressure.resize(NumRC);
268     RegLimit.resize(NumRC);
269     std::fill(RegPressure.begin(), RegPressure.end(), 0);
270     for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
271            E = TRI->regclass_end(); I != E; ++I)
272       RegLimit[(*I)->getID()] = TLI->getRegPressureLimit(*I, MF);
273   }
274
275   // Get our Loop information...
276   MLI = &getAnalysis<MachineLoopInfo>();
277   DT  = &getAnalysis<MachineDominatorTree>();
278   AA  = &getAnalysis<AliasAnalysis>();
279
280   SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
281   while (!Worklist.empty()) {
282     CurLoop = Worklist.pop_back_val();
283     CurPreheader = 0;
284
285     // If this is done before regalloc, only visit outer-most preheader-sporting
286     // loops.
287     if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
288       Worklist.append(CurLoop->begin(), CurLoop->end());
289       continue;
290     }
291
292     if (!PreRegAlloc)
293       HoistRegionPostRA();
294     else {
295       // CSEMap is initialized for loop header when the first instruction is
296       // being hoisted.
297       MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
298       FirstInLoop = true;
299       HoistRegion(N);
300       CSEMap.clear();
301     }
302   }
303
304   return Changed;
305 }
306
307 /// InstructionStoresToFI - Return true if instruction stores to the
308 /// specified frame.
309 static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
310   for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
311          oe = MI->memoperands_end(); o != oe; ++o) {
312     if (!(*o)->isStore() || !(*o)->getValue())
313       continue;
314     if (const FixedStackPseudoSourceValue *Value =
315         dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
316       if (Value->getFrameIndex() == FI)
317         return true;
318     }
319   }
320   return false;
321 }
322
323 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
324 /// gather register def and frame object update information.
325 void MachineLICM::ProcessMI(MachineInstr *MI,
326                             unsigned *PhysRegDefs,
327                             SmallSet<int, 32> &StoredFIs,
328                             SmallVector<CandidateInfo, 32> &Candidates) {
329   bool RuledOut = false;
330   bool HasNonInvariantUse = false;
331   unsigned Def = 0;
332   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
333     const MachineOperand &MO = MI->getOperand(i);
334     if (MO.isFI()) {
335       // Remember if the instruction stores to the frame index.
336       int FI = MO.getIndex();
337       if (!StoredFIs.count(FI) &&
338           MFI->isSpillSlotObjectIndex(FI) &&
339           InstructionStoresToFI(MI, FI))
340         StoredFIs.insert(FI);
341       HasNonInvariantUse = true;
342       continue;
343     }
344
345     if (!MO.isReg())
346       continue;
347     unsigned Reg = MO.getReg();
348     if (!Reg)
349       continue;
350     assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
351            "Not expecting virtual register!");
352
353     if (!MO.isDef()) {
354       if (Reg && PhysRegDefs[Reg])
355         // If it's using a non-loop-invariant register, then it's obviously not
356         // safe to hoist.
357         HasNonInvariantUse = true;
358       continue;
359     }
360
361     if (MO.isImplicit()) {
362       ++PhysRegDefs[Reg];
363       for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
364         ++PhysRegDefs[*AS];
365       if (!MO.isDead())
366         // Non-dead implicit def? This cannot be hoisted.
367         RuledOut = true;
368       // No need to check if a dead implicit def is also defined by
369       // another instruction.
370       continue;
371     }
372
373     // FIXME: For now, avoid instructions with multiple defs, unless
374     // it's a dead implicit def.
375     if (Def)
376       RuledOut = true;
377     else
378       Def = Reg;
379
380     // If we have already seen another instruction that defines the same
381     // register, then this is not safe.
382     if (++PhysRegDefs[Reg] > 1)
383       // MI defined register is seen defined by another instruction in
384       // the loop, it cannot be a LICM candidate.
385       RuledOut = true;
386     for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
387       if (++PhysRegDefs[*AS] > 1)
388         RuledOut = true;
389   }
390
391   // Only consider reloads for now and remats which do not have register
392   // operands. FIXME: Consider unfold load folding instructions.
393   if (Def && !RuledOut) {
394     int FI = INT_MIN;
395     if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
396         (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
397       Candidates.push_back(CandidateInfo(MI, Def, FI));
398   }
399 }
400
401 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
402 /// invariants out to the preheader.
403 void MachineLICM::HoistRegionPostRA() {
404   unsigned NumRegs = TRI->getNumRegs();
405   unsigned *PhysRegDefs = new unsigned[NumRegs];
406   std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
407
408   SmallVector<CandidateInfo, 32> Candidates;
409   SmallSet<int, 32> StoredFIs;
410
411   // Walk the entire region, count number of defs for each register, and
412   // collect potential LICM candidates.
413   const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
414   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
415     MachineBasicBlock *BB = Blocks[i];
416     // Conservatively treat live-in's as an external def.
417     // FIXME: That means a reload that're reused in successor block(s) will not
418     // be LICM'ed.
419     for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
420            E = BB->livein_end(); I != E; ++I) {
421       unsigned Reg = *I;
422       ++PhysRegDefs[Reg];
423       for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
424         ++PhysRegDefs[*AS];
425     }
426
427     for (MachineBasicBlock::iterator
428            MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
429       MachineInstr *MI = &*MII;
430       ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
431     }
432   }
433
434   // Now evaluate whether the potential candidates qualify.
435   // 1. Check if the candidate defined register is defined by another
436   //    instruction in the loop.
437   // 2. If the candidate is a load from stack slot (always true for now),
438   //    check if the slot is stored anywhere in the loop.
439   for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
440     if (Candidates[i].FI != INT_MIN &&
441         StoredFIs.count(Candidates[i].FI))
442       continue;
443
444     if (PhysRegDefs[Candidates[i].Def] == 1) {
445       bool Safe = true;
446       MachineInstr *MI = Candidates[i].MI;
447       for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
448         const MachineOperand &MO = MI->getOperand(j);
449         if (!MO.isReg() || MO.isDef() || !MO.getReg())
450           continue;
451         if (PhysRegDefs[MO.getReg()]) {
452           // If it's using a non-loop-invariant register, then it's obviously
453           // not safe to hoist.
454           Safe = false;
455           break;
456         }
457       }
458       if (Safe)
459         HoistPostRA(MI, Candidates[i].Def);
460     }
461   }
462
463   delete[] PhysRegDefs;
464 }
465
466 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
467 /// loop, and make sure it is not killed by any instructions in the loop.
468 void MachineLICM::AddToLiveIns(unsigned Reg) {
469   const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
470   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
471     MachineBasicBlock *BB = Blocks[i];
472     if (!BB->isLiveIn(Reg))
473       BB->addLiveIn(Reg);
474     for (MachineBasicBlock::iterator
475            MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
476       MachineInstr *MI = &*MII;
477       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
478         MachineOperand &MO = MI->getOperand(i);
479         if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
480         if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
481           MO.setIsKill(false);
482       }
483     }
484   }
485 }
486
487 /// HoistPostRA - When an instruction is found to only use loop invariant
488 /// operands that is safe to hoist, this instruction is called to do the
489 /// dirty work.
490 void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
491   MachineBasicBlock *Preheader = getCurPreheader();
492   if (!Preheader) return;
493
494   // Now move the instructions to the predecessor, inserting it before any
495   // terminator instructions.
496   DEBUG({
497       dbgs() << "Hoisting " << *MI;
498       if (Preheader->getBasicBlock())
499         dbgs() << " to MachineBasicBlock "
500                << Preheader->getName();
501       if (MI->getParent()->getBasicBlock())
502         dbgs() << " from MachineBasicBlock "
503                << MI->getParent()->getName();
504       dbgs() << "\n";
505     });
506
507   // Splice the instruction to the preheader.
508   MachineBasicBlock *MBB = MI->getParent();
509   Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
510
511   // Add register to livein list to all the BBs in the current loop since a 
512   // loop invariant must be kept live throughout the whole loop. This is
513   // important to ensure later passes do not scavenge the def register.
514   AddToLiveIns(Def);
515
516   ++NumPostRAHoisted;
517   Changed = true;
518 }
519
520 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
521 /// dominated by the specified block, and that are in the current loop) in depth
522 /// first order w.r.t the DominatorTree. This allows us to visit definitions
523 /// before uses, allowing us to hoist a loop body in one pass without iteration.
524 ///
525 void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
526   assert(N != 0 && "Null dominator tree node?");
527   MachineBasicBlock *BB = N->getBlock();
528
529   // If this subregion is not in the top level loop at all, exit.
530   if (!CurLoop->contains(BB)) return;
531
532   MachineBasicBlock *Preheader = getCurPreheader();
533   if (Preheader) {
534     if (TrackRegPressure)
535       InitRegPressure(BB);
536
537     for (MachineBasicBlock::iterator
538            MII = BB->begin(), E = BB->end(); MII != E; ) {
539       MachineBasicBlock::iterator NextMII = MII; ++NextMII;
540       MachineInstr *MI = &*MII;
541
542       if (TrackRegPressure)
543         UpdateRegPressureBefore(MI);
544       Hoist(MI, Preheader);
545       if (TrackRegPressure)
546         UpdateRegPressureAfter(MI);
547
548       MII = NextMII;
549     }
550   }
551
552   // Don't hoist things out of a large switch statement.  This often causes
553   // code to be hoisted that wasn't going to be executed, and increases
554   // register pressure in a situation where it's likely to matter.
555   if (BB->succ_size() < 25) {
556     const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
557     for (unsigned I = 0, E = Children.size(); I != E; ++I)
558       HoistRegion(Children[I]);
559   }
560 }
561
562 /// InitRegPressure - Find all virtual register references that are livein to
563 /// the block to initialize the starting "register pressure". Note this does
564 /// not count live through (livein but not used) registers.
565 void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
566   SmallSet<unsigned, 16> Seen;
567
568   std::fill(RegPressure.begin(), RegPressure.end(), 0);
569   for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
570        MII != E; ++MII) {
571     MachineInstr *MI = &*MII;
572     for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
573       const MachineOperand &MO = MI->getOperand(i);
574       if (!MO.isReg() || MO.isImplicit())
575         continue;
576       unsigned Reg = MO.getReg();
577       if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
578         continue;
579       if (!Seen.insert(Reg))
580         continue;
581
582       // Must be a livein.
583       const TargetRegisterClass *RC = MRI->getRegClass(Reg);
584       EVT VT = *RC->vt_begin();
585       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
586       RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
587     }
588   }
589 }
590
591 /// UpdateRegPressureBefore / UpdateRegPressureAfter - Update estimate of
592 /// register pressure before and after executing a specifi instruction.
593 void MachineLICM::UpdateRegPressureBefore(const MachineInstr *MI) {
594   if (MI->isImplicitDef() || MI->isPHI())
595     return;
596
597   for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
598     const MachineOperand &MO = MI->getOperand(i);
599     if (!MO.isReg() || MO.isImplicit() || !MO.isUse() || !MO.isKill())
600       continue;
601     unsigned Reg = MO.getReg();
602     if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
603       continue;
604
605     const TargetRegisterClass *RC = MRI->getRegClass(Reg);
606     EVT VT = *RC->vt_begin();
607     unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
608     unsigned RCCost = TLI->getRepRegClassCostFor(VT);
609
610     assert(RCCost <= RegPressure[RCId]);
611     RegPressure[RCId] -= RCCost;
612   }
613 }
614
615 void MachineLICM::UpdateRegPressureAfter(const MachineInstr *MI) {
616   if (MI->isImplicitDef() || MI->isPHI())
617     return;
618
619   for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
620     const MachineOperand &MO = MI->getOperand(i);
621     if (!MO.isReg() || MO.isImplicit() || !MO.isDef())
622       continue;
623     unsigned Reg = MO.getReg();
624     if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
625       continue;
626
627     const TargetRegisterClass *RC = MRI->getRegClass(Reg);
628     EVT VT = *RC->vt_begin();
629     unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
630     unsigned RCCost = TLI->getRepRegClassCostFor(VT);
631     RegPressure[RCId] += RCCost;
632   }
633 }
634
635 /// IsLICMCandidate - Returns true if the instruction may be a suitable
636 /// candidate for LICM. e.g. If the instruction is a call, then it's obviously
637 /// not safe to hoist it.
638 bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
639   // Check if it's safe to move the instruction.
640   bool DontMoveAcrossStore = true;
641   if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
642     return false;
643   
644   return true;
645 }
646
647 /// IsLoopInvariantInst - Returns true if the instruction is loop
648 /// invariant. I.e., all virtual register operands are defined outside of the
649 /// loop, physical registers aren't accessed explicitly, and there are no side
650 /// effects that aren't captured by the operands or other flags.
651 /// 
652 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
653   if (!IsLICMCandidate(I))
654     return false;
655
656   // The instruction is loop invariant if all of its operands are.
657   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
658     const MachineOperand &MO = I.getOperand(i);
659
660     if (!MO.isReg())
661       continue;
662
663     unsigned Reg = MO.getReg();
664     if (Reg == 0) continue;
665
666     // Don't hoist an instruction that uses or defines a physical register.
667     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
668       if (MO.isUse()) {
669         // If the physreg has no defs anywhere, it's just an ambient register
670         // and we can freely move its uses. Alternatively, if it's allocatable,
671         // it could get allocated to something with a def during allocation.
672         if (!MRI->def_empty(Reg))
673           return false;
674         if (AllocatableSet.test(Reg))
675           return false;
676         // Check for a def among the register's aliases too.
677         for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
678           unsigned AliasReg = *Alias;
679           if (!MRI->def_empty(AliasReg))
680             return false;
681           if (AllocatableSet.test(AliasReg))
682             return false;
683         }
684         // Otherwise it's safe to move.
685         continue;
686       } else if (!MO.isDead()) {
687         // A def that isn't dead. We can't move it.
688         return false;
689       } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
690         // If the reg is live into the loop, we can't hoist an instruction
691         // which would clobber it.
692         return false;
693       }
694     }
695
696     if (!MO.isUse())
697       continue;
698
699     assert(MRI->getVRegDef(Reg) &&
700            "Machine instr not mapped for this vreg?!");
701
702     // If the loop contains the definition of an operand, then the instruction
703     // isn't loop invariant.
704     if (CurLoop->contains(MRI->getVRegDef(Reg)))
705       return false;
706   }
707
708   // If we got this far, the instruction is loop invariant!
709   return true;
710 }
711
712
713 /// HasPHIUses - Return true if the specified register has any PHI use.
714 static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *MRI) {
715   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
716          UE = MRI->use_end(); UI != UE; ++UI) {
717     MachineInstr *UseMI = &*UI;
718     if (UseMI->isPHI())
719       return true;
720   }
721   return false;
722 }
723
724 /// isLoadFromConstantMemory - Return true if the given instruction is a
725 /// load from constant memory. Machine LICM will hoist these even if they are
726 /// not re-materializable.
727 bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
728   if (!MI->getDesc().mayLoad()) return false;
729   if (!MI->hasOneMemOperand()) return false;
730   MachineMemOperand *MMO = *MI->memoperands_begin();
731   if (MMO->isVolatile()) return false;
732   if (!MMO->getValue()) return false;
733   const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
734   if (PSV) {
735     MachineFunction &MF = *MI->getParent()->getParent();
736     return PSV->isConstant(MF.getFrameInfo());
737   } else {
738     return AA->pointsToConstantMemory(MMO->getValue());
739   }
740 }
741
742 /// ComputeOperandLatency - Compute operand latency between a def of 'Reg'
743 /// and an use in the current loop.
744 int MachineLICM::ComputeOperandLatency(MachineInstr &MI,
745                                        unsigned DefIdx, unsigned Reg) {
746   if (MRI->use_nodbg_empty(Reg))
747     // No use? Return arbitrary large number!
748     return 300;
749
750   int Latency = -1;
751   for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
752          E = MRI->use_nodbg_end(); I != E; ++I) {
753     MachineInstr *UseMI = &*I;
754     if (!CurLoop->contains(UseMI->getParent()))
755       continue;
756     for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
757       const MachineOperand &MO = UseMI->getOperand(i);
758       if (!MO.isReg() || !MO.isUse())
759         continue;
760       unsigned MOReg = MO.getReg();
761       if (MOReg != Reg)
762         continue;
763
764       int UseCycle = TII->getOperandLatency(InstrItins, &MI, DefIdx, UseMI, i);
765       Latency = std::max(Latency, UseCycle);
766     }
767
768     if (Latency != -1)
769       break;
770   }
771
772   if (Latency == -1)
773     Latency = InstrItins->getOperandCycle(MI.getDesc().getSchedClass(), DefIdx);
774
775   return Latency;
776 }
777
778 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
779 /// the given loop invariant.
780 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
781   if (MI.isImplicitDef())
782     return true;
783
784   // FIXME: For now, only hoist re-materilizable instructions. LICM will
785   // increase register pressure. We want to make sure it doesn't increase
786   // spilling.
787   // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
788   // these tend to help performance in low register pressure situation. The
789   // trade off is it may cause spill in high pressure situation. It will end up
790   // adding a store in the loop preheader. But the reload is no more expensive.
791   // The side benefit is these loads are frequently CSE'ed.
792   if (!TrackRegPressure || MI.getDesc().isAsCheapAsAMove()) {
793     if (!TII->isTriviallyReMaterializable(&MI, AA) &&
794         !isLoadFromConstantMemory(&MI))
795       return false;
796   } else {
797     // In low register pressure situation, we can be more aggressive about 
798     // hoisting. Also, favors hoisting long latency instructions even in
799     // moderately high pressure situation.
800     int Delta = 0;
801     for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
802       const MachineOperand &MO = MI.getOperand(i);
803       if (!MO.isReg() || MO.isImplicit())
804         continue;
805       unsigned Reg = MO.getReg();
806       if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
807         continue;
808       const TargetRegisterClass *RC = MRI->getRegClass(Reg);
809       EVT VT = *RC->vt_begin();
810       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
811       unsigned RCCost = TLI->getRepRegClassCostFor(VT);
812
813       if (MO.isUse()) {
814         if (RegPressure[RCId] >= RegLimit[RCId]) {
815           // Hoisting this instruction may actually reduce register pressure
816           // in the loop.
817           int Pressure = RegPressure[RCId] - RCCost;
818           assert(Pressure >= 0);
819           Delta -= (int)RegLimit[RCId] - Pressure;
820         }
821       } else {
822         if (InstrItins && !InstrItins->isEmpty()) {
823           int Cycle = ComputeOperandLatency(MI, i, Reg);
824           if (Cycle > 3)
825             // FIXME: Target specific high latency limit?
826             return true;
827         }
828         if (RegPressure[RCId] >= RegLimit[RCId])
829           Delta += RCCost;
830         else {
831           int Pressure = RegPressure[RCId] + RCCost;
832           if (Pressure > (int)RegLimit[RCId])
833             Delta += Pressure - RegLimit[RCId];
834         }
835       }
836     }
837
838     if (Delta >= 0)
839       return true;
840
841     // High register pressure situation, only hoist if the instruction is going to
842     // be remat'ed.
843     if (!TII->isTriviallyReMaterializable(&MI, AA) &&
844         !isLoadFromConstantMemory(&MI))
845       return false;
846   }
847
848   // If result(s) of this instruction is used by PHIs, then don't hoist it.
849   // The presence of joins makes it difficult for current register allocator
850   // implementation to perform remat.
851   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
852     const MachineOperand &MO = MI.getOperand(i);
853     if (!MO.isReg() || !MO.isDef())
854       continue;
855     if (HasPHIUses(MO.getReg(), MRI))
856       return false;
857   }
858
859   return true;
860 }
861
862 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
863   // Don't unfold simple loads.
864   if (MI->getDesc().canFoldAsLoad())
865     return 0;
866
867   // If not, we may be able to unfold a load and hoist that.
868   // First test whether the instruction is loading from an amenable
869   // memory location.
870   if (!isLoadFromConstantMemory(MI))
871     return 0;
872
873   // Next determine the register class for a temporary register.
874   unsigned LoadRegIndex;
875   unsigned NewOpc =
876     TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
877                                     /*UnfoldLoad=*/true,
878                                     /*UnfoldStore=*/false,
879                                     &LoadRegIndex);
880   if (NewOpc == 0) return 0;
881   const TargetInstrDesc &TID = TII->get(NewOpc);
882   if (TID.getNumDefs() != 1) return 0;
883   const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
884   // Ok, we're unfolding. Create a temporary register and do the unfold.
885   unsigned Reg = MRI->createVirtualRegister(RC);
886
887   MachineFunction &MF = *MI->getParent()->getParent();
888   SmallVector<MachineInstr *, 2> NewMIs;
889   bool Success =
890     TII->unfoldMemoryOperand(MF, MI, Reg,
891                              /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
892                              NewMIs);
893   (void)Success;
894   assert(Success &&
895          "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
896          "succeeded!");
897   assert(NewMIs.size() == 2 &&
898          "Unfolded a load into multiple instructions!");
899   MachineBasicBlock *MBB = MI->getParent();
900   MBB->insert(MI, NewMIs[0]);
901   MBB->insert(MI, NewMIs[1]);
902   // If unfolding produced a load that wasn't loop-invariant or profitable to
903   // hoist, discard the new instructions and bail.
904   if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
905     NewMIs[0]->eraseFromParent();
906     NewMIs[1]->eraseFromParent();
907     return 0;
908   }
909   // Otherwise we successfully unfolded a load that we can hoist.
910   MI->eraseFromParent();
911   return NewMIs[0];
912 }
913
914 void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
915   for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
916     const MachineInstr *MI = &*I;
917     // FIXME: For now, only hoist re-materilizable instructions. LICM will
918     // increase register pressure. We want to make sure it doesn't increase
919     // spilling.
920     if (TII->isTriviallyReMaterializable(MI, AA)) {
921       unsigned Opcode = MI->getOpcode();
922       DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
923         CI = CSEMap.find(Opcode);
924       if (CI != CSEMap.end())
925         CI->second.push_back(MI);
926       else {
927         std::vector<const MachineInstr*> CSEMIs;
928         CSEMIs.push_back(MI);
929         CSEMap.insert(std::make_pair(Opcode, CSEMIs));
930       }
931     }
932   }
933 }
934
935 const MachineInstr*
936 MachineLICM::LookForDuplicate(const MachineInstr *MI,
937                               std::vector<const MachineInstr*> &PrevMIs) {
938   for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
939     const MachineInstr *PrevMI = PrevMIs[i];
940     if (TII->produceSameValue(MI, PrevMI))
941       return PrevMI;
942   }
943   return 0;
944 }
945
946 bool MachineLICM::EliminateCSE(MachineInstr *MI,
947           DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
948   // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
949   // the undef property onto uses.
950   if (CI == CSEMap.end() || MI->isImplicitDef())
951     return false;
952
953   if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
954     DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
955
956     // Replace virtual registers defined by MI by their counterparts defined
957     // by Dup.
958     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
959       const MachineOperand &MO = MI->getOperand(i);
960
961       // Physical registers may not differ here.
962       assert((!MO.isReg() || MO.getReg() == 0 ||
963               !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
964               MO.getReg() == Dup->getOperand(i).getReg()) &&
965              "Instructions with different phys regs are not identical!");
966
967       if (MO.isReg() && MO.isDef() &&
968           !TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
969         MRI->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
970         MRI->clearKillFlags(Dup->getOperand(i).getReg());
971       }
972     }
973     MI->eraseFromParent();
974     ++NumCSEed;
975     return true;
976   }
977   return false;
978 }
979
980 /// Hoist - When an instruction is found to use only loop invariant operands
981 /// that are safe to hoist, this instruction is called to do the dirty work.
982 ///
983 void MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
984   // First check whether we should hoist this instruction.
985   if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
986     // If not, try unfolding a hoistable load.
987     MI = ExtractHoistableLoad(MI);
988     if (!MI) return;
989   }
990
991   // Now move the instructions to the predecessor, inserting it before any
992   // terminator instructions.
993   DEBUG({
994       dbgs() << "Hoisting " << *MI;
995       if (Preheader->getBasicBlock())
996         dbgs() << " to MachineBasicBlock "
997                << Preheader->getName();
998       if (MI->getParent()->getBasicBlock())
999         dbgs() << " from MachineBasicBlock "
1000                << MI->getParent()->getName();
1001       dbgs() << "\n";
1002     });
1003
1004   // If this is the first instruction being hoisted to the preheader,
1005   // initialize the CSE map with potential common expressions.
1006   if (FirstInLoop) {
1007     InitCSEMap(Preheader);
1008     FirstInLoop = false;
1009   }
1010
1011   // Look for opportunity to CSE the hoisted instruction.
1012   unsigned Opcode = MI->getOpcode();
1013   DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1014     CI = CSEMap.find(Opcode);
1015   if (!EliminateCSE(MI, CI)) {
1016     // Otherwise, splice the instruction to the preheader.
1017     Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
1018
1019     // Clear the kill flags of any register this instruction defines,
1020     // since they may need to be live throughout the entire loop
1021     // rather than just live for part of it.
1022     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1023       MachineOperand &MO = MI->getOperand(i);
1024       if (MO.isReg() && MO.isDef() && !MO.isDead())
1025         MRI->clearKillFlags(MO.getReg());
1026     }
1027
1028     // Add to the CSE map.
1029     if (CI != CSEMap.end())
1030       CI->second.push_back(MI);
1031     else {
1032       std::vector<const MachineInstr*> CSEMIs;
1033       CSEMIs.push_back(MI);
1034       CSEMap.insert(std::make_pair(Opcode, CSEMIs));
1035     }
1036   }
1037
1038   ++NumHoisted;
1039   Changed = true;
1040 }
1041
1042 MachineBasicBlock *MachineLICM::getCurPreheader() {
1043   // Determine the block to which to hoist instructions. If we can't find a
1044   // suitable loop predecessor, we can't do any hoisting.
1045
1046   // If we've tried to get a preheader and failed, don't try again.
1047   if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1048     return 0;
1049
1050   if (!CurPreheader) {
1051     CurPreheader = CurLoop->getLoopPreheader();
1052     if (!CurPreheader) {
1053       MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1054       if (!Pred) {
1055         CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1056         return 0;
1057       }
1058
1059       CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1060       if (!CurPreheader) {
1061         CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1062         return 0;
1063       }
1064     }
1065   }
1066   return CurPreheader;
1067 }