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