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