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