Add option -licm-const-load to hoist all loads from constant memory.
[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/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineDominators.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/Statistic.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
40
41 using namespace llvm;
42
43 static cl::opt<bool> HoistLdConst("licm-const-load",
44                                   cl::desc("LICM load from constant memory"),
45                                   cl::init(false), cl::Hidden);
46
47 STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
48 STATISTIC(NumCSEed,   "Number of hoisted machine instructions CSEed");
49
50 namespace {
51   class MachineLICM : public MachineFunctionPass {
52     MachineConstantPool *MCP;
53     const TargetMachine   *TM;
54     const TargetInstrInfo *TII;
55     const TargetRegisterInfo *TRI;
56     BitVector AllocatableSet;
57
58     // Various analyses that we use...
59     AliasAnalysis        *AA;      // Alias analysis info.
60     MachineLoopInfo      *LI;      // Current MachineLoopInfo
61     MachineDominatorTree *DT;      // Machine dominator tree for the cur loop
62     MachineRegisterInfo  *RegInfo; // Machine register information
63
64     // State that is updated as we process loops
65     bool         Changed;          // True if a loop is changed.
66     bool         FirstInLoop;      // True if it's the first LICM in the loop.
67     MachineLoop *CurLoop;          // The current loop we are working on.
68     MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
69
70     // For each opcode, keep a list of potentail CSE instructions.
71     DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
72   public:
73     static char ID; // Pass identification, replacement for typeid
74     MachineLICM() : MachineFunctionPass(&ID) {}
75
76     virtual bool runOnMachineFunction(MachineFunction &MF);
77
78     const char *getPassName() const { return "Machine Instruction LICM"; }
79
80     // FIXME: Loop preheaders?
81     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
82       AU.setPreservesCFG();
83       AU.addRequired<MachineLoopInfo>();
84       AU.addRequired<MachineDominatorTree>();
85       AU.addRequired<AliasAnalysis>();
86       AU.addPreserved<MachineLoopInfo>();
87       AU.addPreserved<MachineDominatorTree>();
88       MachineFunctionPass::getAnalysisUsage(AU);
89     }
90
91     virtual void releaseMemory() {
92       CSEMap.clear();
93     }
94
95   private:
96     /// IsLoopInvariantInst - Returns true if the instruction is loop
97     /// invariant. I.e., all virtual register operands are defined outside of
98     /// the loop, physical registers aren't accessed (explicitly or implicitly),
99     /// and the instruction is hoistable.
100     /// 
101     bool IsLoopInvariantInst(MachineInstr &I);
102
103     /// IsProfitableToHoist - Return true if it is potentially profitable to
104     /// hoist the given loop invariant.
105     bool IsProfitableToHoist(MachineInstr &MI, bool &isConstLd);
106
107     /// HoistRegion - Walk the specified region of the CFG (defined by all
108     /// blocks dominated by the specified block, and that are in the current
109     /// loop) in depth first order w.r.t the DominatorTree. This allows us to
110     /// visit definitions before uses, allowing us to hoist a loop body in one
111     /// pass without iteration.
112     ///
113     void HoistRegion(MachineDomTreeNode *N);
114
115     /// isLoadFromConstantMemory - Return true if the given instruction is a
116     /// load from constant memory.
117     bool isLoadFromConstantMemory(MachineInstr *MI);
118
119     /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
120     /// the load itself could be hoisted. Return the unfolded and hoistable
121     /// load, or null if the load couldn't be unfolded or if it wouldn't
122     /// be hoistable.
123     MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
124
125     /// LookForDuplicate - Find an instruction amount PrevMIs that is a
126     /// duplicate of MI. Return this instruction if it's found.
127     const MachineInstr *LookForDuplicate(const MachineInstr *MI,
128                                      std::vector<const MachineInstr*> &PrevMIs);
129
130     /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
131     /// the preheader that compute the same value. If it's found, do a RAU on
132     /// with the definition of the existing instruction rather than hoisting
133     /// the instruction to the preheader.
134     bool EliminateCSE(MachineInstr *MI,
135            DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
136
137     /// Hoist - When an instruction is found to only use loop invariant operands
138     /// that is safe to hoist, this instruction is called to do the dirty work.
139     ///
140     void Hoist(MachineInstr *MI);
141
142     /// InitCSEMap - Initialize the CSE map with instructions that are in the
143     /// current loop preheader that may become duplicates of instructions that
144     /// are hoisted out of the loop.
145     void InitCSEMap(MachineBasicBlock *BB);
146   };
147 } // end anonymous namespace
148
149 char MachineLICM::ID = 0;
150 static RegisterPass<MachineLICM>
151 X("machinelicm", "Machine Loop Invariant Code Motion");
152
153 FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
154
155 /// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
156 /// loop that has a preheader.
157 static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
158   for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
159     if (L->getLoopPreheader())
160       return false;
161   return true;
162 }
163
164 /// Hoist expressions out of the specified loop. Note, alias info for inner loop
165 /// is not preserved so it is not a good idea to run LICM multiple times on one
166 /// loop.
167 ///
168 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
169   DEBUG(errs() << "******** Machine LICM ********\n");
170
171   Changed = FirstInLoop = false;
172   MCP = MF.getConstantPool();
173   TM = &MF.getTarget();
174   TII = TM->getInstrInfo();
175   TRI = TM->getRegisterInfo();
176   RegInfo = &MF.getRegInfo();
177   AllocatableSet = TRI->getAllocatableSet(MF);
178
179   // Get our Loop information...
180   LI = &getAnalysis<MachineLoopInfo>();
181   DT = &getAnalysis<MachineDominatorTree>();
182   AA = &getAnalysis<AliasAnalysis>();
183
184   for (MachineLoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
185     CurLoop = *I;
186
187     // Only visit outer-most preheader-sporting loops.
188     if (!LoopIsOuterMostWithPreheader(CurLoop))
189       continue;
190
191     // Determine the block to which to hoist instructions. If we can't find a
192     // suitable loop preheader, we can't do any hoisting.
193     //
194     // FIXME: We are only hoisting if the basic block coming into this loop
195     // has only one successor. This isn't the case in general because we haven't
196     // broken critical edges or added preheaders.
197     CurPreheader = CurLoop->getLoopPreheader();
198     if (!CurPreheader)
199       continue;
200
201     // CSEMap is initialized for loop header when the first instruction is
202     // being hoisted.
203     FirstInLoop = true;
204     HoistRegion(DT->getNode(CurLoop->getHeader()));
205     CSEMap.clear();
206   }
207
208   return Changed;
209 }
210
211 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
212 /// dominated by the specified block, and that are in the current loop) in depth
213 /// first order w.r.t the DominatorTree. This allows us to visit definitions
214 /// before uses, allowing us to hoist a loop body in one pass without iteration.
215 ///
216 void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
217   assert(N != 0 && "Null dominator tree node?");
218   MachineBasicBlock *BB = N->getBlock();
219
220   // If this subregion is not in the top level loop at all, exit.
221   if (!CurLoop->contains(BB)) return;
222
223   for (MachineBasicBlock::iterator
224          MII = BB->begin(), E = BB->end(); MII != E; ) {
225     MachineBasicBlock::iterator NextMII = MII; ++NextMII;
226     Hoist(&*MII);
227     MII = NextMII;
228   }
229
230   const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
231
232   for (unsigned I = 0, E = Children.size(); I != E; ++I)
233     HoistRegion(Children[I]);
234 }
235
236 /// IsLoopInvariantInst - Returns true if the instruction is loop
237 /// invariant. I.e., all virtual register operands are defined outside of the
238 /// loop, physical registers aren't accessed explicitly, and there are no side
239 /// effects that aren't captured by the operands or other flags.
240 /// 
241 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
242   const TargetInstrDesc &TID = I.getDesc();
243   
244   // Ignore stuff that we obviously can't hoist.
245   if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
246       TID.hasUnmodeledSideEffects())
247     return false;
248
249   if (TID.mayLoad()) {
250     // Okay, this instruction does a load. As a refinement, we allow the target
251     // to decide whether the loaded value is actually a constant. If so, we can
252     // actually use it as a load.
253     if (!I.isInvariantLoad(AA))
254       // FIXME: we should be able to hoist loads with no other side effects if
255       // there are no other instructions which can change memory in this loop.
256       // This is a trivial form of alias analysis.
257       return false;
258   }
259
260   DEBUG({
261       errs() << "--- Checking if we can hoist " << I;
262       if (I.getDesc().getImplicitUses()) {
263         errs() << "  * Instruction has implicit uses:\n";
264
265         const TargetRegisterInfo *TRI = TM->getRegisterInfo();
266         for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
267              *ImpUses; ++ImpUses)
268           errs() << "      -> " << TRI->getName(*ImpUses) << "\n";
269       }
270
271       if (I.getDesc().getImplicitDefs()) {
272         errs() << "  * Instruction has implicit defines:\n";
273
274         const TargetRegisterInfo *TRI = TM->getRegisterInfo();
275         for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
276              *ImpDefs; ++ImpDefs)
277           errs() << "      -> " << TRI->getName(*ImpDefs) << "\n";
278       }
279     });
280
281   if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
282     DEBUG(errs() << "Cannot hoist with implicit defines or uses\n");
283     return false;
284   }
285
286   // The instruction is loop invariant if all of its operands are.
287   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
288     const MachineOperand &MO = I.getOperand(i);
289
290     if (!MO.isReg())
291       continue;
292
293     unsigned Reg = MO.getReg();
294     if (Reg == 0) continue;
295
296     // Don't hoist an instruction that uses or defines a physical register.
297     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
298       if (MO.isUse()) {
299         // If the physreg has no defs anywhere, it's just an ambient register
300         // and we can freely move its uses. Alternatively, if it's allocatable,
301         // it could get allocated to something with a def during allocation.
302         if (!RegInfo->def_empty(Reg))
303           return false;
304         if (AllocatableSet.test(Reg))
305           return false;
306         // Check for a def among the register's aliases too.
307         for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
308           unsigned AliasReg = *Alias;
309           if (!RegInfo->def_empty(AliasReg))
310             return false;
311           if (AllocatableSet.test(AliasReg))
312             return false;
313         }
314         // Otherwise it's safe to move.
315         continue;
316       } else if (!MO.isDead()) {
317         // A def that isn't dead. We can't move it.
318         return false;
319       }
320     }
321
322     if (!MO.isUse())
323       continue;
324
325     assert(RegInfo->getVRegDef(Reg) &&
326            "Machine instr not mapped for this vreg?!");
327
328     // If the loop contains the definition of an operand, then the instruction
329     // isn't loop invariant.
330     if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
331       return false;
332   }
333
334   // If we got this far, the instruction is loop invariant!
335   return true;
336 }
337
338
339 /// HasPHIUses - Return true if the specified register has any PHI use.
340 static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
341   for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
342          UE = RegInfo->use_end(); UI != UE; ++UI) {
343     MachineInstr *UseMI = &*UI;
344     if (UseMI->getOpcode() == TargetInstrInfo::PHI)
345       return true;
346   }
347   return false;
348 }
349
350 /// isLoadFromConstantMemory - Return true if the given instruction is a
351 /// load from constant memory. Machine LICM will hoist these even if they are
352 /// not re-materializable.
353 bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
354   if (!MI->getDesc().mayLoad()) return false;
355   if (!MI->hasOneMemOperand()) return false;
356   MachineMemOperand *MMO = *MI->memoperands_begin();
357   if (MMO->isVolatile()) return false;
358   if (!MMO->getValue()) return false;
359   const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
360   if (PSV) {
361     MachineFunction &MF = *MI->getParent()->getParent();
362     return PSV->isConstant(MF.getFrameInfo());
363   } else {
364     return AA->pointsToConstantMemory(MMO->getValue());
365   }
366 }
367
368 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
369 /// the given loop invariant.
370 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI, bool &isConstLd) {
371   isConstLd = false;
372
373   if (MI.getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
374     return false;
375
376   // FIXME: For now, only hoist re-materilizable instructions. LICM will
377   // increase register pressure. We want to make sure it doesn't increase
378   // spilling.
379   // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
380   // these tend to help performance in low register pressure situation. The
381   // trade off is it may cause spill in high pressure situation. It will end up
382   // adding a store in the loop preheader. But the reload is no more expensive.
383   // The side benefit is these loads are frequently CSE'ed.
384   if (!TII->isTriviallyReMaterializable(&MI, AA)) {
385     if (!HoistLdConst || !isLoadFromConstantMemory(&MI))
386       return false;
387     isConstLd = true;
388   }
389
390   // If result(s) of this instruction is used by PHIs, then don't hoist it.
391   // The presence of joins makes it difficult for current register allocator
392   // implementation to perform remat.
393   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
394     const MachineOperand &MO = MI.getOperand(i);
395     if (!MO.isReg() || !MO.isDef())
396       continue;
397     if (HasPHIUses(MO.getReg(), RegInfo))
398       return false;
399   }
400
401   return true;
402 }
403
404 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
405   // If not, we may be able to unfold a load and hoist that.
406   // First test whether the instruction is loading from an amenable
407   // memory location.
408   if (!isLoadFromConstantMemory(MI))
409     return 0;
410
411   // Next determine the register class for a temporary register.
412   unsigned LoadRegIndex;
413   unsigned NewOpc =
414     TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
415                                     /*UnfoldLoad=*/true,
416                                     /*UnfoldStore=*/false,
417                                     &LoadRegIndex);
418   if (NewOpc == 0) return 0;
419   const TargetInstrDesc &TID = TII->get(NewOpc);
420   if (TID.getNumDefs() != 1) return 0;
421   const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
422   // Ok, we're unfolding. Create a temporary register and do the unfold.
423   unsigned Reg = RegInfo->createVirtualRegister(RC);
424
425   MachineFunction &MF = *MI->getParent()->getParent();
426   SmallVector<MachineInstr *, 2> NewMIs;
427   bool Success =
428     TII->unfoldMemoryOperand(MF, MI, Reg,
429                              /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
430                              NewMIs);
431   (void)Success;
432   assert(Success &&
433          "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
434          "succeeded!");
435   assert(NewMIs.size() == 2 &&
436          "Unfolded a load into multiple instructions!");
437   MachineBasicBlock *MBB = MI->getParent();
438   MBB->insert(MI, NewMIs[0]);
439   MBB->insert(MI, NewMIs[1]);
440   // If unfolding produced a load that wasn't loop-invariant or profitable to
441   // hoist, discard the new instructions and bail.
442   bool isConstLd;
443   if (!IsLoopInvariantInst(*NewMIs[0]) ||
444       !IsProfitableToHoist(*NewMIs[0], isConstLd)) {
445     NewMIs[0]->eraseFromParent();
446     NewMIs[1]->eraseFromParent();
447     return 0;
448   }
449   // Otherwise we successfully unfolded a load that we can hoist.
450   MI->eraseFromParent();
451   return NewMIs[0];
452 }
453
454 void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
455   for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
456     const MachineInstr *MI = &*I;
457     // FIXME: For now, only hoist re-materilizable instructions. LICM will
458     // increase register pressure. We want to make sure it doesn't increase
459     // spilling.
460     if (TII->isTriviallyReMaterializable(MI, AA)) {
461       unsigned Opcode = MI->getOpcode();
462       DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
463         CI = CSEMap.find(Opcode);
464       if (CI != CSEMap.end())
465         CI->second.push_back(MI);
466       else {
467         std::vector<const MachineInstr*> CSEMIs;
468         CSEMIs.push_back(MI);
469         CSEMap.insert(std::make_pair(Opcode, CSEMIs));
470       }
471     }
472   }
473 }
474
475 const MachineInstr*
476 MachineLICM::LookForDuplicate(const MachineInstr *MI,
477                               std::vector<const MachineInstr*> &PrevMIs) {
478   for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
479     const MachineInstr *PrevMI = PrevMIs[i];
480     if (TII->isIdentical(MI, PrevMI, RegInfo))
481       return PrevMI;
482   }
483   return 0;
484 }
485
486 bool MachineLICM::EliminateCSE(MachineInstr *MI,
487           DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
488   if (CI == CSEMap.end())
489     return false;
490
491   if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
492     DEBUG(errs() << "CSEing " << *MI << " with " << *Dup);
493     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
494       const MachineOperand &MO = MI->getOperand(i);
495       if (MO.isReg() && MO.isDef())
496         RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
497     }
498     MI->eraseFromParent();
499     ++NumCSEed;
500     return true;
501   }
502   return false;
503 }
504
505 /// Hoist - When an instruction is found to use only loop invariant operands
506 /// that are safe to hoist, this instruction is called to do the dirty work.
507 ///
508 void MachineLICM::Hoist(MachineInstr *MI) {
509   // First check whether we should hoist this instruction.
510   bool isConstLd;
511   if (!IsLoopInvariantInst(*MI) ||
512       !IsProfitableToHoist(*MI, isConstLd)) {
513     // If not, try unfolding a hoistable load.
514     MI = ExtractHoistableLoad(MI);
515     if (!MI) return;
516   }
517
518   // Now move the instructions to the predecessor, inserting it before any
519   // terminator instructions.
520   DEBUG({
521       errs() << "Hoisting ";
522       if (isConstLd)
523         errs() << "load from constant mem ";
524       errs() << *MI;
525       if (CurPreheader->getBasicBlock())
526         errs() << " to MachineBasicBlock "
527                << CurPreheader->getName();
528       if (MI->getParent()->getBasicBlock())
529         errs() << " from MachineBasicBlock "
530                << MI->getParent()->getName();
531       errs() << "\n";
532     });
533
534   // If this is the first instruction being hoisted to the preheader,
535   // initialize the CSE map with potential common expressions.
536   InitCSEMap(CurPreheader);
537
538   // Look for opportunity to CSE the hoisted instruction.
539   unsigned Opcode = MI->getOpcode();
540   DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
541     CI = CSEMap.find(Opcode);
542   if (!EliminateCSE(MI, CI)) {
543     // Otherwise, splice the instruction to the preheader.
544     CurPreheader->splice(CurPreheader->getFirstTerminator(),MI->getParent(),MI);
545
546     // Add to the CSE map.
547     if (CI != CSEMap.end())
548       CI->second.push_back(MI);
549     else {
550       std::vector<const MachineInstr*> CSEMIs;
551       CSEMIs.push_back(MI);
552       CSEMap.insert(std::make_pair(Opcode, CSEMIs));
553     }
554   }
555
556   ++NumHoisted;
557   Changed = true;
558 }