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