Delete this obsolete comment.
[oota-llvm.git] / lib / CodeGen / MachineLICM.cpp
1 //===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass performs loop invariant code motion on machine instructions. We
11 // attempt to remove as much code from the body of a loop as possible.
12 //
13 // This pass does not attempt to throttle itself to limit register pressure.
14 // The register allocation phases are expected to perform rematerialization
15 // to recover when register pressure is high.
16 //
17 // This pass is not intended to be a replacement or a complete alternative
18 // for the LLVM-IR-level LICM pass. It is only designed to hoist simple
19 // constructs that are not exposed before lowering and instruction selection.
20 //
21 //===----------------------------------------------------------------------===//
22
23 #define DEBUG_TYPE "machine-licm"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineLoopInfo.h"
28 #include "llvm/CodeGen/MachineMemOperand.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/PseudoSourceValue.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Analysis/AliasAnalysis.h"
35 #include "llvm/ADT/DenseMap.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
40
41 using namespace llvm;
42
43 STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
44 STATISTIC(NumCSEed,   "Number of hoisted machine instructions CSEed");
45 STATISTIC(NumPostRAHoisted,
46           "Number of machine instructions hoisted out of loops post regalloc");
47
48 namespace {
49   class MachineLICM : public MachineFunctionPass {
50     bool PreRegAlloc;
51
52     const TargetMachine   *TM;
53     const TargetInstrInfo *TII;
54     const TargetRegisterInfo *TRI;
55     const MachineFrameInfo *MFI;
56     MachineRegisterInfo *RegInfo;
57
58     // Various analyses that we use...
59     AliasAnalysis        *AA;      // Alias analysis info.
60     MachineLoopInfo      *MLI;     // Current MachineLoopInfo
61     MachineDominatorTree *DT;      // Machine dominator tree for the cur loop
62
63     // State that is updated as we process loops
64     bool         Changed;          // True if a loop is changed.
65     MachineLoop *CurLoop;          // The current loop we are working on.
66     MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
67
68     BitVector AllocatableSet;
69
70     // For each opcode, keep a list of potentail CSE instructions.
71     DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
72
73   public:
74     static char ID; // Pass identification, replacement for typeid
75     MachineLICM() :
76       MachineFunctionPass(&ID), PreRegAlloc(true) {}
77
78     explicit MachineLICM(bool PreRA) :
79       MachineFunctionPass(&ID), PreRegAlloc(PreRA) {}
80
81     virtual bool runOnMachineFunction(MachineFunction &MF);
82
83     const char *getPassName() const { return "Machine Instruction LICM"; }
84
85     // FIXME: Loop preheaders?
86     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
87       AU.setPreservesCFG();
88       AU.addRequired<MachineLoopInfo>();
89       AU.addRequired<MachineDominatorTree>();
90       AU.addRequired<AliasAnalysis>();
91       AU.addPreserved<MachineLoopInfo>();
92       AU.addPreserved<MachineDominatorTree>();
93       MachineFunctionPass::getAnalysisUsage(AU);
94     }
95
96     virtual void releaseMemory() {
97       CSEMap.clear();
98     }
99
100   private:
101     /// CandidateInfo - Keep track of information about hoisting candidates.
102     struct CandidateInfo {
103       MachineInstr *MI;
104       int           FI;
105       unsigned      Def;
106       CandidateInfo(MachineInstr *mi, int fi, unsigned def)
107         : MI(mi), FI(fi), Def(def) {}
108     };
109
110     /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
111     /// invariants out to the preheader.
112     void HoistRegionPostRA(MachineDomTreeNode *N);
113
114     /// HoistPostRA - When an instruction is found to only use loop invariant
115     /// operands that is safe to hoist, this instruction is called to do the
116     /// dirty work.
117     void HoistPostRA(MachineInstr *MI, unsigned Def);
118
119     /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
120     /// gather register def and frame object update information.
121     void ProcessMI(MachineInstr *MI, unsigned *PhysRegDefs,
122                    SmallSet<int, 32> &StoredFIs,
123                    SmallVector<CandidateInfo, 32> &Candidates);
124
125     /// AddToLiveIns - Add 'Reg' to the livein sets of BBs in the backedge path
126     /// from MBB to LoopHeader (inclusive).
127     void AddToLiveIns(unsigned Reg,
128                       MachineBasicBlock *MBB, MachineBasicBlock *LoopHeader);    
129
130     /// IsLoopInvariantInst - Returns true if the instruction is loop
131     /// invariant. I.e., all virtual register operands are defined outside of
132     /// the loop, physical registers aren't accessed (explicitly or implicitly),
133     /// and the instruction is hoistable.
134     /// 
135     bool IsLoopInvariantInst(MachineInstr &I);
136
137     /// IsProfitableToHoist - Return true if it is potentially profitable to
138     /// hoist the given loop invariant.
139     bool IsProfitableToHoist(MachineInstr &MI);
140
141     /// HoistRegion - Walk the specified region of the CFG (defined by all
142     /// blocks dominated by the specified block, and that are in the current
143     /// loop) in depth first order w.r.t the DominatorTree. This allows us to
144     /// visit definitions before uses, allowing us to hoist a loop body in one
145     /// pass without iteration.
146     ///
147     void HoistRegion(MachineDomTreeNode *N);
148
149     /// isLoadFromConstantMemory - Return true if the given instruction is a
150     /// load from constant memory.
151     bool isLoadFromConstantMemory(MachineInstr *MI);
152
153     /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
154     /// the load itself could be hoisted. Return the unfolded and hoistable
155     /// load, or null if the load couldn't be unfolded or if it wouldn't
156     /// be hoistable.
157     MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
158
159     /// LookForDuplicate - Find an instruction amount PrevMIs that is a
160     /// duplicate of MI. Return this instruction if it's found.
161     const MachineInstr *LookForDuplicate(const MachineInstr *MI,
162                                      std::vector<const MachineInstr*> &PrevMIs);
163
164     /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
165     /// the preheader that compute the same value. If it's found, do a RAU on
166     /// with the definition of the existing instruction rather than hoisting
167     /// the instruction to the preheader.
168     bool EliminateCSE(MachineInstr *MI,
169            DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
170
171     /// Hoist - When an instruction is found to only use loop invariant operands
172     /// that is safe to hoist, this instruction is called to do the dirty work.
173     ///
174     void Hoist(MachineInstr *MI);
175
176     /// InitCSEMap - Initialize the CSE map with instructions that are in the
177     /// current loop preheader that may become duplicates of instructions that
178     /// are hoisted out of the loop.
179     void InitCSEMap(MachineBasicBlock *BB);
180   };
181 } // end anonymous namespace
182
183 char MachineLICM::ID = 0;
184 static RegisterPass<MachineLICM>
185 X("machinelicm", "Machine Loop Invariant Code Motion");
186
187 FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
188   return new MachineLICM(PreRegAlloc);
189 }
190
191 /// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
192 /// loop that has a preheader.
193 static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
194   for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
195     if (L->getLoopPreheader())
196       return false;
197   return true;
198 }
199
200 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
201   if (PreRegAlloc)
202     DEBUG(dbgs() << "******** Pre-regalloc Machine LICM ********\n");
203   else
204     DEBUG(dbgs() << "******** Post-regalloc Machine LICM ********\n");
205
206   Changed = false;
207   TM = &MF.getTarget();
208   TII = TM->getInstrInfo();
209   TRI = TM->getRegisterInfo();
210   MFI = MF.getFrameInfo();
211   RegInfo = &MF.getRegInfo();
212   AllocatableSet = TRI->getAllocatableSet(MF);
213
214   // Get our Loop information...
215   MLI = &getAnalysis<MachineLoopInfo>();
216   DT  = &getAnalysis<MachineDominatorTree>();
217   AA  = &getAnalysis<AliasAnalysis>();
218
219   for (MachineLoopInfo::iterator I = MLI->begin(), E = MLI->end(); I != E; ++I){
220     CurLoop = *I;
221
222     // If this is done before regalloc, only visit outer-most preheader-sporting
223     // loops.
224     if (PreRegAlloc && !LoopIsOuterMostWithPreheader(CurLoop))
225       continue;
226
227     // Determine the block to which to hoist instructions. If we can't find a
228     // suitable loop preheader, we can't do any hoisting.
229     //
230     // FIXME: We are only hoisting if the basic block coming into this loop
231     // has only one successor. This isn't the case in general because we haven't
232     // broken critical edges or added preheaders.
233     CurPreheader = CurLoop->getLoopPreheader();
234     if (!CurPreheader)
235       continue;
236
237     // CSEMap is initialized for loop header when the first instruction is
238     // being hoisted.
239     MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
240     if (!PreRegAlloc)
241       HoistRegionPostRA(N);
242     else {
243       HoistRegion(N);
244       CSEMap.clear();
245     }
246   }
247
248   return Changed;
249 }
250
251 /// InstructionStoresToFI - Return true if instruction stores to the
252 /// specified frame.
253 static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
254   for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
255          oe = MI->memoperands_end(); o != oe; ++o) {
256     if (!(*o)->isStore() || !(*o)->getValue())
257       continue;
258     if (const FixedStackPseudoSourceValue *Value =
259         dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
260       if (Value->getFrameIndex() == FI)
261         return true;
262     }
263   }
264   return false;
265 }
266
267 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
268 /// gather register def and frame object update information.
269 void MachineLICM::ProcessMI(MachineInstr *MI,
270                             unsigned *PhysRegDefs,
271                             SmallSet<int, 32> &StoredFIs,
272                             SmallVector<CandidateInfo, 32> &Candidates) {
273   bool RuledOut = false;
274   unsigned Def = 0;
275   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
276     const MachineOperand &MO = MI->getOperand(i);
277     if (MO.isFI()) {
278       // Remember if the instruction stores to the frame index.
279       int FI = MO.getIndex();
280       if (!StoredFIs.count(FI) &&
281           MFI->isSpillSlotObjectIndex(FI) &&
282           InstructionStoresToFI(MI, FI))
283         StoredFIs.insert(FI);
284       continue;
285     }
286
287     if (!MO.isReg())
288       continue;
289     unsigned Reg = MO.getReg();
290     if (!Reg)
291       continue;
292     assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
293            "Not expecting virtual register!");
294
295     if (!MO.isDef())
296       continue;
297
298     if (MO.isImplicit()) {
299       ++PhysRegDefs[Reg];
300       for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
301         ++PhysRegDefs[*AS];
302       if (!MO.isDead())
303         // Non-dead implicit def? This cannot be hoisted.
304         RuledOut = true;
305       // No need to check if a dead implicit def is also defined by
306       // another instruction.
307       continue;
308     }
309
310     // FIXME: For now, avoid instructions with multiple defs, unless
311     // it's a dead implicit def.
312     if (Def)
313       RuledOut = true;
314     else
315       Def = Reg;
316
317     // If we have already seen another instruction that defines the same
318     // register, then this is not safe.
319     if (++PhysRegDefs[Reg] > 1)
320       // MI defined register is seen defined by another instruction in
321       // the loop, it cannot be a LICM candidate.
322       RuledOut = true;
323     for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
324       if (++PhysRegDefs[*AS] > 1)
325         RuledOut = true;
326   }
327
328   // FIXME: Only consider reloads for now. We should be able to handle
329   // remats which does not have register operands.
330   if (Def && !RuledOut) {
331     int FI;
332     if (TII->isLoadFromStackSlot(MI, FI) &&
333         MFI->isSpillSlotObjectIndex(FI))
334       Candidates.push_back(CandidateInfo(MI, FI, Def));
335   }
336 }
337
338 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
339 /// invariants out to the preheader.
340 void MachineLICM::HoistRegionPostRA(MachineDomTreeNode *N) {
341   assert(N != 0 && "Null dominator tree node?");
342
343   unsigned NumRegs = TRI->getNumRegs();
344   unsigned *PhysRegDefs = new unsigned[NumRegs];
345   std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
346
347   SmallVector<CandidateInfo, 32> Candidates;
348   SmallSet<int, 32> StoredFIs;
349
350   // Walk the entire region, count number of defs for each register, and
351   // return potential LICM candidates.
352   SmallVector<MachineDomTreeNode*, 8> WorkList;
353   WorkList.push_back(N);
354   do {
355     N = WorkList.pop_back_val();
356     MachineBasicBlock *BB = N->getBlock();
357
358     if (!CurLoop->contains(MLI->getLoopFor(BB)))
359       continue;
360     // Conservatively treat live-in's as an external def.
361     // FIXME: That means a reload that're reused in successor block(s) will not
362     // be LICM'ed.
363     for (MachineBasicBlock::const_livein_iterator I = BB->livein_begin(),
364            E = BB->livein_end(); I != E; ++I) {
365       unsigned Reg = *I;
366       ++PhysRegDefs[Reg];
367       for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
368         ++PhysRegDefs[*AS];
369     }
370
371     for (MachineBasicBlock::iterator
372            MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
373       MachineInstr *MI = &*MII;
374       ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
375     }
376
377     const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
378     for (unsigned I = 0, E = Children.size(); I != E; ++I)
379       WorkList.push_back(Children[I]);
380   } while (!WorkList.empty());
381
382   // Now evaluate whether the potential candidates qualify.
383   // 1. Check if the candidate defined register is defined by another
384   //    instruction in the loop.
385   // 2. If the candidate is a load from stack slot (always true for now),
386   //    check if the slot is stored anywhere in the loop.
387   for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
388     if (StoredFIs.count(Candidates[i].FI))
389       continue;
390
391     if (PhysRegDefs[Candidates[i].Def] == 1)
392       HoistPostRA(Candidates[i].MI, Candidates[i].Def);
393   }
394 }
395
396 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
397 /// backedge path from MBB to LoopHeader.
398 void MachineLICM::AddToLiveIns(unsigned Reg, MachineBasicBlock *MBB,
399                                MachineBasicBlock *LoopHeader) {
400   SmallPtrSet<MachineBasicBlock*, 4> Visited;
401   SmallVector<MachineBasicBlock*, 4> WorkList;
402   WorkList.push_back(MBB);
403   do {
404     MBB = WorkList.pop_back_val();
405     if (!Visited.insert(MBB))
406       continue;
407     MBB->addLiveIn(Reg);
408     if (MBB == LoopHeader)
409       continue;
410     for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
411            E = MBB->pred_end(); PI != E; ++PI)
412       WorkList.push_back(*PI);
413   } while (!WorkList.empty());
414 }
415
416 /// HoistPostRA - When an instruction is found to only use loop invariant
417 /// operands that is safe to hoist, this instruction is called to do the
418 /// dirty work.
419 void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
420   // Now move the instructions to the predecessor, inserting it before any
421   // terminator instructions.
422   DEBUG({
423       dbgs() << "Hoisting " << *MI;
424       if (CurPreheader->getBasicBlock())
425         dbgs() << " to MachineBasicBlock "
426                << CurPreheader->getName();
427       if (MI->getParent()->getBasicBlock())
428         dbgs() << " from MachineBasicBlock "
429                << MI->getParent()->getName();
430       dbgs() << "\n";
431     });
432
433   // Splice the instruction to the preheader.
434   MachineBasicBlock *MBB = MI->getParent();
435   CurPreheader->splice(CurPreheader->getFirstTerminator(), MBB, MI);
436
437   // Add register to livein list to BBs in the path from loop header to original
438   // BB. Note, currently it's not necessary to worry about adding it to all BB's
439   // with uses. Reload that're reused in successor block(s) are not being
440   // hoisted.
441   AddToLiveIns(Def, MBB, CurLoop->getHeader());
442
443   ++NumPostRAHoisted;
444   Changed = true;
445 }
446
447 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
448 /// dominated by the specified block, and that are in the current loop) in depth
449 /// first order w.r.t the DominatorTree. This allows us to visit definitions
450 /// before uses, allowing us to hoist a loop body in one pass without iteration.
451 ///
452 void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
453   assert(N != 0 && "Null dominator tree node?");
454   MachineBasicBlock *BB = N->getBlock();
455
456   // If this subregion is not in the top level loop at all, exit.
457   if (!CurLoop->contains(BB)) return;
458
459   for (MachineBasicBlock::iterator
460          MII = BB->begin(), E = BB->end(); MII != E; ) {
461     MachineBasicBlock::iterator NextMII = MII; ++NextMII;
462     Hoist(&*MII);
463     MII = NextMII;
464   }
465
466   const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
467   for (unsigned I = 0, E = Children.size(); I != E; ++I)
468     HoistRegion(Children[I]);
469 }
470
471 /// IsLoopInvariantInst - Returns true if the instruction is loop
472 /// invariant. I.e., all virtual register operands are defined outside of the
473 /// loop, physical registers aren't accessed explicitly, and there are no side
474 /// effects that aren't captured by the operands or other flags.
475 /// 
476 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
477   const TargetInstrDesc &TID = I.getDesc();
478   
479   // Ignore stuff that we obviously can't hoist.
480   if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
481       TID.hasUnmodeledSideEffects())
482     return false;
483
484   if (TID.mayLoad()) {
485     // Okay, this instruction does a load. As a refinement, we allow the target
486     // to decide whether the loaded value is actually a constant. If so, we can
487     // actually use it as a load.
488     if (!I.isInvariantLoad(AA))
489       // FIXME: we should be able to hoist loads with no other side effects if
490       // there are no other instructions which can change memory in this loop.
491       // This is a trivial form of alias analysis.
492       return false;
493   }
494
495   // The instruction is loop invariant if all of its operands are.
496   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
497     const MachineOperand &MO = I.getOperand(i);
498
499     if (!MO.isReg())
500       continue;
501
502     unsigned Reg = MO.getReg();
503     if (Reg == 0) continue;
504
505     // Don't hoist an instruction that uses or defines a physical register.
506     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
507       if (MO.isUse()) {
508         // If the physreg has no defs anywhere, it's just an ambient register
509         // and we can freely move its uses. Alternatively, if it's allocatable,
510         // it could get allocated to something with a def during allocation.
511         if (!RegInfo->def_empty(Reg))
512           return false;
513         if (AllocatableSet.test(Reg))
514           return false;
515         // Check for a def among the register's aliases too.
516         for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
517           unsigned AliasReg = *Alias;
518           if (!RegInfo->def_empty(AliasReg))
519             return false;
520           if (AllocatableSet.test(AliasReg))
521             return false;
522         }
523         // Otherwise it's safe to move.
524         continue;
525       } else if (!MO.isDead()) {
526         // A def that isn't dead. We can't move it.
527         return false;
528       } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
529         // If the reg is live into the loop, we can't hoist an instruction
530         // which would clobber it.
531         return false;
532       }
533     }
534
535     if (!MO.isUse())
536       continue;
537
538     assert(RegInfo->getVRegDef(Reg) &&
539            "Machine instr not mapped for this vreg?!");
540
541     // If the loop contains the definition of an operand, then the instruction
542     // isn't loop invariant.
543     if (CurLoop->contains(RegInfo->getVRegDef(Reg)))
544       return false;
545   }
546
547   // If we got this far, the instruction is loop invariant!
548   return true;
549 }
550
551
552 /// HasPHIUses - Return true if the specified register has any PHI use.
553 static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
554   for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
555          UE = RegInfo->use_end(); UI != UE; ++UI) {
556     MachineInstr *UseMI = &*UI;
557     if (UseMI->isPHI())
558       return true;
559   }
560   return false;
561 }
562
563 /// isLoadFromConstantMemory - Return true if the given instruction is a
564 /// load from constant memory. Machine LICM will hoist these even if they are
565 /// not re-materializable.
566 bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
567   if (!MI->getDesc().mayLoad()) return false;
568   if (!MI->hasOneMemOperand()) return false;
569   MachineMemOperand *MMO = *MI->memoperands_begin();
570   if (MMO->isVolatile()) return false;
571   if (!MMO->getValue()) return false;
572   const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
573   if (PSV) {
574     MachineFunction &MF = *MI->getParent()->getParent();
575     return PSV->isConstant(MF.getFrameInfo());
576   } else {
577     return AA->pointsToConstantMemory(MMO->getValue());
578   }
579 }
580
581 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
582 /// the given loop invariant.
583 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
584   if (MI.isImplicitDef())
585     return false;
586
587   // FIXME: For now, only hoist re-materilizable instructions. LICM will
588   // increase register pressure. We want to make sure it doesn't increase
589   // spilling.
590   // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
591   // these tend to help performance in low register pressure situation. The
592   // trade off is it may cause spill in high pressure situation. It will end up
593   // adding a store in the loop preheader. But the reload is no more expensive.
594   // The side benefit is these loads are frequently CSE'ed.
595   if (!TII->isTriviallyReMaterializable(&MI, AA)) {
596     if (!isLoadFromConstantMemory(&MI))
597       return false;
598   }
599
600   // If result(s) of this instruction is used by PHIs, then don't hoist it.
601   // The presence of joins makes it difficult for current register allocator
602   // implementation to perform remat.
603   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
604     const MachineOperand &MO = MI.getOperand(i);
605     if (!MO.isReg() || !MO.isDef())
606       continue;
607     if (HasPHIUses(MO.getReg(), RegInfo))
608       return false;
609   }
610
611   return true;
612 }
613
614 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
615   // If not, we may be able to unfold a load and hoist that.
616   // First test whether the instruction is loading from an amenable
617   // memory location.
618   if (!isLoadFromConstantMemory(MI))
619     return 0;
620
621   // Next determine the register class for a temporary register.
622   unsigned LoadRegIndex;
623   unsigned NewOpc =
624     TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
625                                     /*UnfoldLoad=*/true,
626                                     /*UnfoldStore=*/false,
627                                     &LoadRegIndex);
628   if (NewOpc == 0) return 0;
629   const TargetInstrDesc &TID = TII->get(NewOpc);
630   if (TID.getNumDefs() != 1) return 0;
631   const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
632   // Ok, we're unfolding. Create a temporary register and do the unfold.
633   unsigned Reg = RegInfo->createVirtualRegister(RC);
634
635   MachineFunction &MF = *MI->getParent()->getParent();
636   SmallVector<MachineInstr *, 2> NewMIs;
637   bool Success =
638     TII->unfoldMemoryOperand(MF, MI, Reg,
639                              /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
640                              NewMIs);
641   (void)Success;
642   assert(Success &&
643          "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
644          "succeeded!");
645   assert(NewMIs.size() == 2 &&
646          "Unfolded a load into multiple instructions!");
647   MachineBasicBlock *MBB = MI->getParent();
648   MBB->insert(MI, NewMIs[0]);
649   MBB->insert(MI, NewMIs[1]);
650   // If unfolding produced a load that wasn't loop-invariant or profitable to
651   // hoist, discard the new instructions and bail.
652   if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
653     NewMIs[0]->eraseFromParent();
654     NewMIs[1]->eraseFromParent();
655     return 0;
656   }
657   // Otherwise we successfully unfolded a load that we can hoist.
658   MI->eraseFromParent();
659   return NewMIs[0];
660 }
661
662 void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
663   for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
664     const MachineInstr *MI = &*I;
665     // FIXME: For now, only hoist re-materilizable instructions. LICM will
666     // increase register pressure. We want to make sure it doesn't increase
667     // spilling.
668     if (TII->isTriviallyReMaterializable(MI, AA)) {
669       unsigned Opcode = MI->getOpcode();
670       DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
671         CI = CSEMap.find(Opcode);
672       if (CI != CSEMap.end())
673         CI->second.push_back(MI);
674       else {
675         std::vector<const MachineInstr*> CSEMIs;
676         CSEMIs.push_back(MI);
677         CSEMap.insert(std::make_pair(Opcode, CSEMIs));
678       }
679     }
680   }
681 }
682
683 const MachineInstr*
684 MachineLICM::LookForDuplicate(const MachineInstr *MI,
685                               std::vector<const MachineInstr*> &PrevMIs) {
686   for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
687     const MachineInstr *PrevMI = PrevMIs[i];
688     if (TII->produceSameValue(MI, PrevMI))
689       return PrevMI;
690   }
691   return 0;
692 }
693
694 bool MachineLICM::EliminateCSE(MachineInstr *MI,
695           DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
696   if (CI == CSEMap.end())
697     return false;
698
699   if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
700     DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
701
702     // Replace virtual registers defined by MI by their counterparts defined
703     // by Dup.
704     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
705       const MachineOperand &MO = MI->getOperand(i);
706
707       // Physical registers may not differ here.
708       assert((!MO.isReg() || MO.getReg() == 0 ||
709               !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
710               MO.getReg() == Dup->getOperand(i).getReg()) &&
711              "Instructions with different phys regs are not identical!");
712
713       if (MO.isReg() && MO.isDef() &&
714           !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
715         RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
716     }
717     MI->eraseFromParent();
718     ++NumCSEed;
719     return true;
720   }
721   return false;
722 }
723
724 /// Hoist - When an instruction is found to use only loop invariant operands
725 /// that are safe to hoist, this instruction is called to do the dirty work.
726 ///
727 void MachineLICM::Hoist(MachineInstr *MI) {
728   // First check whether we should hoist this instruction.
729   if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
730     // If not, try unfolding a hoistable load.
731     MI = ExtractHoistableLoad(MI);
732     if (!MI) return;
733   }
734
735   // Now move the instructions to the predecessor, inserting it before any
736   // terminator instructions.
737   DEBUG({
738       dbgs() << "Hoisting " << *MI;
739       if (CurPreheader->getBasicBlock())
740         dbgs() << " to MachineBasicBlock "
741                << CurPreheader->getName();
742       if (MI->getParent()->getBasicBlock())
743         dbgs() << " from MachineBasicBlock "
744                << MI->getParent()->getName();
745       dbgs() << "\n";
746     });
747
748   // If this is the first instruction being hoisted to the preheader,
749   // initialize the CSE map with potential common expressions.
750   InitCSEMap(CurPreheader);
751
752   // Look for opportunity to CSE the hoisted instruction.
753   unsigned Opcode = MI->getOpcode();
754   DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
755     CI = CSEMap.find(Opcode);
756   if (!EliminateCSE(MI, CI)) {
757     // Otherwise, splice the instruction to the preheader.
758     CurPreheader->splice(CurPreheader->getFirstTerminator(),MI->getParent(),MI);
759
760     // Add to the CSE map.
761     if (CI != CSEMap.end())
762       CI->second.push_back(MI);
763     else {
764       std::vector<const MachineInstr*> CSEMIs;
765       CSEMIs.push_back(MI);
766       CSEMap.insert(std::make_pair(Opcode, CSEMIs));
767     }
768   }
769
770   ++NumHoisted;
771   Changed = true;
772 }