MachineCSE.cpp revision c36b7069b42bece963b7e6adf020353ce990ef76
1//===-- MachineCSE.cpp - Machine Common Subexpression Elimination 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 global common subexpression elimination on machine
11// instructions using a scoped hash table based value numbering scheme. It
12// must be run while the machine function is still in SSA form.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "machine-cse"
17#include "llvm/CodeGen/Passes.h"
18#include "llvm/CodeGen/MachineDominators.h"
19#include "llvm/CodeGen/MachineInstr.h"
20#include "llvm/CodeGen/MachineRegisterInfo.h"
21#include "llvm/Analysis/AliasAnalysis.h"
22#include "llvm/Target/TargetInstrInfo.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/ScopedHashTable.h"
25#include "llvm/ADT/SmallSet.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/RecyclingAllocator.h"
29
30using namespace llvm;
31
32STATISTIC(NumCoalesces, "Number of copies coalesced");
33STATISTIC(NumCSEs,      "Number of common subexpression eliminated");
34STATISTIC(NumPhysCSEs,
35          "Number of physreg referencing common subexpr eliminated");
36STATISTIC(NumCommutes,  "Number of copies coalesced after commuting");
37
38namespace {
39  class MachineCSE : public MachineFunctionPass {
40    const TargetInstrInfo *TII;
41    const TargetRegisterInfo *TRI;
42    AliasAnalysis *AA;
43    MachineDominatorTree *DT;
44    MachineRegisterInfo *MRI;
45  public:
46    static char ID; // Pass identification
47    MachineCSE() : MachineFunctionPass(ID), LookAheadLimit(5), CurrVN(0) {
48      initializeMachineCSEPass(*PassRegistry::getPassRegistry());
49    }
50
51    virtual bool runOnMachineFunction(MachineFunction &MF);
52
53    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
54      AU.setPreservesCFG();
55      MachineFunctionPass::getAnalysisUsage(AU);
56      AU.addRequired<AliasAnalysis>();
57      AU.addPreservedID(MachineLoopInfoID);
58      AU.addRequired<MachineDominatorTree>();
59      AU.addPreserved<MachineDominatorTree>();
60    }
61
62    virtual void releaseMemory() {
63      ScopeMap.clear();
64      Exps.clear();
65    }
66
67  private:
68    const unsigned LookAheadLimit;
69    typedef RecyclingAllocator<BumpPtrAllocator,
70        ScopedHashTableVal<MachineInstr*, unsigned> > AllocatorTy;
71    typedef ScopedHashTable<MachineInstr*, unsigned,
72        MachineInstrExpressionTrait, AllocatorTy> ScopedHTType;
73    typedef ScopedHTType::ScopeTy ScopeType;
74    DenseMap<MachineBasicBlock*, ScopeType*> ScopeMap;
75    ScopedHTType VNT;
76    SmallVector<MachineInstr*, 64> Exps;
77    unsigned CurrVN;
78
79    bool PerformTrivialCoalescing(MachineInstr *MI, MachineBasicBlock *MBB);
80    bool isPhysDefTriviallyDead(unsigned Reg,
81                                MachineBasicBlock::const_iterator I,
82                                MachineBasicBlock::const_iterator E) const ;
83    bool hasLivePhysRegDefUses(const MachineInstr *MI,
84                               const MachineBasicBlock *MBB,
85                               SmallSet<unsigned,8> &PhysRefs) const;
86    bool PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
87                          SmallSet<unsigned,8> &PhysRefs) const;
88    bool isCSECandidate(MachineInstr *MI);
89    bool isProfitableToCSE(unsigned CSReg, unsigned Reg,
90                           MachineInstr *CSMI, MachineInstr *MI);
91    void EnterScope(MachineBasicBlock *MBB);
92    void ExitScope(MachineBasicBlock *MBB);
93    bool ProcessBlock(MachineBasicBlock *MBB);
94    void ExitScopeIfDone(MachineDomTreeNode *Node,
95                 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
96                 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap);
97    bool PerformCSE(MachineDomTreeNode *Node);
98  };
99} // end anonymous namespace
100
101char MachineCSE::ID = 0;
102INITIALIZE_PASS_BEGIN(MachineCSE, "machine-cse",
103                "Machine Common Subexpression Elimination", false, false)
104INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
105INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
106INITIALIZE_PASS_END(MachineCSE, "machine-cse",
107                "Machine Common Subexpression Elimination", false, false)
108
109FunctionPass *llvm::createMachineCSEPass() { return new MachineCSE(); }
110
111bool MachineCSE::PerformTrivialCoalescing(MachineInstr *MI,
112                                          MachineBasicBlock *MBB) {
113  bool Changed = false;
114  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
115    MachineOperand &MO = MI->getOperand(i);
116    if (!MO.isReg() || !MO.isUse())
117      continue;
118    unsigned Reg = MO.getReg();
119    if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
120      continue;
121    if (!MRI->hasOneNonDBGUse(Reg))
122      // Only coalesce single use copies. This ensure the copy will be
123      // deleted.
124      continue;
125    MachineInstr *DefMI = MRI->getVRegDef(Reg);
126    if (DefMI->getParent() != MBB)
127      continue;
128    if (!DefMI->isCopy())
129      continue;
130    unsigned SrcReg = DefMI->getOperand(1).getReg();
131    if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
132      continue;
133    if (DefMI->getOperand(0).getSubReg() || DefMI->getOperand(1).getSubReg())
134      continue;
135    if (!MRI->constrainRegClass(SrcReg, MRI->getRegClass(Reg)))
136      continue;
137    DEBUG(dbgs() << "Coalescing: " << *DefMI);
138    DEBUG(dbgs() << "***     to: " << *MI);
139    MO.setReg(SrcReg);
140    MRI->clearKillFlags(SrcReg);
141    DefMI->eraseFromParent();
142    ++NumCoalesces;
143    Changed = true;
144  }
145
146  return Changed;
147}
148
149bool
150MachineCSE::isPhysDefTriviallyDead(unsigned Reg,
151                                   MachineBasicBlock::const_iterator I,
152                                   MachineBasicBlock::const_iterator E) const {
153  unsigned LookAheadLeft = LookAheadLimit;
154  while (LookAheadLeft) {
155    // Skip over dbg_value's.
156    while (I != E && I->isDebugValue())
157      ++I;
158
159    if (I == E)
160      // Reached end of block, register is obviously dead.
161      return true;
162
163    bool SeenDef = false;
164    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
165      const MachineOperand &MO = I->getOperand(i);
166      if (!MO.isReg() || !MO.getReg())
167        continue;
168      if (!TRI->regsOverlap(MO.getReg(), Reg))
169        continue;
170      if (MO.isUse())
171        // Found a use!
172        return false;
173      SeenDef = true;
174    }
175    if (SeenDef)
176      // See a def of Reg (or an alias) before encountering any use, it's
177      // trivially dead.
178      return true;
179
180    --LookAheadLeft;
181    ++I;
182  }
183  return false;
184}
185
186/// hasLivePhysRegDefUses - Return true if the specified instruction read/write
187/// physical registers (except for dead defs of physical registers). It also
188/// returns the physical register def by reference if it's the only one and the
189/// instruction does not uses a physical register.
190bool MachineCSE::hasLivePhysRegDefUses(const MachineInstr *MI,
191                                       const MachineBasicBlock *MBB,
192                                       SmallSet<unsigned,8> &PhysRefs) const {
193  MachineBasicBlock::const_iterator I = MI; I = llvm::next(I);
194  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
195    const MachineOperand &MO = MI->getOperand(i);
196    if (!MO.isReg())
197      continue;
198    unsigned Reg = MO.getReg();
199    if (!Reg)
200      continue;
201    if (TargetRegisterInfo::isVirtualRegister(Reg))
202      continue;
203    // If the def is dead, it's ok. But the def may not marked "dead". That's
204    // common since this pass is run before livevariables. We can scan
205    // forward a few instructions and check if it is obviously dead.
206    if (MO.isDef() &&
207        (MO.isDead() || isPhysDefTriviallyDead(Reg, I, MBB->end())))
208      continue;
209    PhysRefs.insert(Reg);
210    for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias)
211      PhysRefs.insert(*Alias);
212  }
213
214  return !PhysRefs.empty();
215}
216
217bool MachineCSE::PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
218                                  SmallSet<unsigned,8> &PhysRefs) const {
219  // For now conservatively returns false if the common subexpression is
220  // not in the same basic block as the given instruction.
221  MachineBasicBlock *MBB = MI->getParent();
222  if (CSMI->getParent() != MBB)
223    return false;
224  MachineBasicBlock::const_iterator I = CSMI; I = llvm::next(I);
225  MachineBasicBlock::const_iterator E = MI;
226  unsigned LookAheadLeft = LookAheadLimit;
227  while (LookAheadLeft) {
228    // Skip over dbg_value's.
229    while (I != E && I->isDebugValue())
230      ++I;
231
232    if (I == E)
233      return true;
234
235    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
236      const MachineOperand &MO = I->getOperand(i);
237      if (!MO.isReg() || !MO.isDef())
238        continue;
239      unsigned MOReg = MO.getReg();
240      if (TargetRegisterInfo::isVirtualRegister(MOReg))
241        continue;
242      if (PhysRefs.count(MOReg))
243        return false;
244    }
245
246    --LookAheadLeft;
247    ++I;
248  }
249
250  return false;
251}
252
253bool MachineCSE::isCSECandidate(MachineInstr *MI) {
254  if (MI->isLabel() || MI->isPHI() || MI->isImplicitDef() ||
255      MI->isKill() || MI->isInlineAsm() || MI->isDebugValue())
256    return false;
257
258  // Ignore copies.
259  if (MI->isCopyLike())
260    return false;
261
262  // Ignore stuff that we obviously can't move.
263  const TargetInstrDesc &TID = MI->getDesc();
264  if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
265      MI->hasUnmodeledSideEffects())
266    return false;
267
268  if (TID.mayLoad()) {
269    // Okay, this instruction does a load. As a refinement, we allow the target
270    // to decide whether the loaded value is actually a constant. If so, we can
271    // actually use it as a load.
272    if (!MI->isInvariantLoad(AA))
273      // FIXME: we should be able to hoist loads with no other side effects if
274      // there are no other instructions which can change memory in this loop.
275      // This is a trivial form of alias analysis.
276      return false;
277  }
278  return true;
279}
280
281/// isProfitableToCSE - Return true if it's profitable to eliminate MI with a
282/// common expression that defines Reg.
283bool MachineCSE::isProfitableToCSE(unsigned CSReg, unsigned Reg,
284                                   MachineInstr *CSMI, MachineInstr *MI) {
285  // FIXME: Heuristics that works around the lack the live range splitting.
286
287  // Heuristics #1: Don't cse "cheap" computating if the def is not local or in an
288  // immediate predecessor. We don't want to increase register pressure and end up
289  // causing other computation to be spilled.
290  if (MI->getDesc().isAsCheapAsAMove()) {
291    MachineBasicBlock *CSBB = CSMI->getParent();
292    MachineBasicBlock *BB = MI->getParent();
293    if (CSBB != BB &&
294        find(CSBB->succ_begin(), CSBB->succ_end(), BB) == CSBB->succ_end())
295      return false;
296  }
297
298  // Heuristics #2: If the expression doesn't not use a vr and the only use
299  // of the redundant computation are copies, do not cse.
300  bool HasVRegUse = false;
301  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
302    const MachineOperand &MO = MI->getOperand(i);
303    if (MO.isReg() && MO.isUse() && MO.getReg() &&
304        TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
305      HasVRegUse = true;
306      break;
307    }
308  }
309  if (!HasVRegUse) {
310    bool HasNonCopyUse = false;
311    for (MachineRegisterInfo::use_nodbg_iterator I =  MRI->use_nodbg_begin(Reg),
312           E = MRI->use_nodbg_end(); I != E; ++I) {
313      MachineInstr *Use = &*I;
314      // Ignore copies.
315      if (!Use->isCopyLike()) {
316        HasNonCopyUse = true;
317        break;
318      }
319    }
320    if (!HasNonCopyUse)
321      return false;
322  }
323
324  // Heuristics #3: If the common subexpression is used by PHIs, do not reuse
325  // it unless the defined value is already used in the BB of the new use.
326  bool HasPHI = false;
327  SmallPtrSet<MachineBasicBlock*, 4> CSBBs;
328  for (MachineRegisterInfo::use_nodbg_iterator I =  MRI->use_nodbg_begin(CSReg),
329       E = MRI->use_nodbg_end(); I != E; ++I) {
330    MachineInstr *Use = &*I;
331    HasPHI |= Use->isPHI();
332    CSBBs.insert(Use->getParent());
333  }
334
335  if (!HasPHI)
336    return true;
337  return CSBBs.count(MI->getParent());
338}
339
340void MachineCSE::EnterScope(MachineBasicBlock *MBB) {
341  DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
342  ScopeType *Scope = new ScopeType(VNT);
343  ScopeMap[MBB] = Scope;
344}
345
346void MachineCSE::ExitScope(MachineBasicBlock *MBB) {
347  DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
348  DenseMap<MachineBasicBlock*, ScopeType*>::iterator SI = ScopeMap.find(MBB);
349  assert(SI != ScopeMap.end());
350  ScopeMap.erase(SI);
351  delete SI->second;
352}
353
354bool MachineCSE::ProcessBlock(MachineBasicBlock *MBB) {
355  bool Changed = false;
356
357  SmallVector<std::pair<unsigned, unsigned>, 8> CSEPairs;
358  for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; ) {
359    MachineInstr *MI = &*I;
360    ++I;
361
362    if (!isCSECandidate(MI))
363      continue;
364
365    bool FoundCSE = VNT.count(MI);
366    if (!FoundCSE) {
367      // Look for trivial copy coalescing opportunities.
368      if (PerformTrivialCoalescing(MI, MBB)) {
369        // After coalescing MI itself may become a copy.
370        if (MI->isCopyLike())
371          continue;
372        FoundCSE = VNT.count(MI);
373      }
374    }
375
376    // Commute commutable instructions.
377    bool Commuted = false;
378    if (!FoundCSE && MI->getDesc().isCommutable()) {
379      MachineInstr *NewMI = TII->commuteInstruction(MI);
380      if (NewMI) {
381        Commuted = true;
382        FoundCSE = VNT.count(NewMI);
383        if (NewMI != MI)
384          // New instruction. It doesn't need to be kept.
385          NewMI->eraseFromParent();
386        else if (!FoundCSE)
387          // MI was changed but it didn't help, commute it back!
388          (void)TII->commuteInstruction(MI);
389      }
390    }
391
392    // If the instruction defines physical registers and the values *may* be
393    // used, then it's not safe to replace it with a common subexpression.
394    // It's also not safe if the instruction uses physical registers.
395    SmallSet<unsigned,8> PhysRefs;
396    if (FoundCSE && hasLivePhysRegDefUses(MI, MBB, PhysRefs)) {
397      FoundCSE = false;
398
399      // ... Unless the CS is local and it also defines the physical register
400      // which is not clobbered in between and the physical register uses
401      // were not clobbered.
402      unsigned CSVN = VNT.lookup(MI);
403      MachineInstr *CSMI = Exps[CSVN];
404      if (PhysRegDefsReach(CSMI, MI, PhysRefs))
405        FoundCSE = true;
406    }
407
408    if (!FoundCSE) {
409      VNT.insert(MI, CurrVN++);
410      Exps.push_back(MI);
411      continue;
412    }
413
414    // Found a common subexpression, eliminate it.
415    unsigned CSVN = VNT.lookup(MI);
416    MachineInstr *CSMI = Exps[CSVN];
417    DEBUG(dbgs() << "Examining: " << *MI);
418    DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI);
419
420    // Check if it's profitable to perform this CSE.
421    bool DoCSE = true;
422    unsigned NumDefs = MI->getDesc().getNumDefs();
423    for (unsigned i = 0, e = MI->getNumOperands(); NumDefs && i != e; ++i) {
424      MachineOperand &MO = MI->getOperand(i);
425      if (!MO.isReg() || !MO.isDef())
426        continue;
427      unsigned OldReg = MO.getReg();
428      unsigned NewReg = CSMI->getOperand(i).getReg();
429      if (OldReg == NewReg)
430        continue;
431      assert(TargetRegisterInfo::isVirtualRegister(OldReg) &&
432             TargetRegisterInfo::isVirtualRegister(NewReg) &&
433             "Do not CSE physical register defs!");
434      if (!isProfitableToCSE(NewReg, OldReg, CSMI, MI)) {
435        DoCSE = false;
436        break;
437      }
438      CSEPairs.push_back(std::make_pair(OldReg, NewReg));
439      --NumDefs;
440    }
441
442    // Actually perform the elimination.
443    if (DoCSE) {
444      for (unsigned i = 0, e = CSEPairs.size(); i != e; ++i) {
445        MRI->replaceRegWith(CSEPairs[i].first, CSEPairs[i].second);
446        MRI->clearKillFlags(CSEPairs[i].second);
447      }
448      MI->eraseFromParent();
449      ++NumCSEs;
450      if (!PhysRefs.empty())
451        ++NumPhysCSEs;
452      if (Commuted)
453        ++NumCommutes;
454    } else {
455      DEBUG(dbgs() << "*** Not profitable, avoid CSE!\n");
456      VNT.insert(MI, CurrVN++);
457      Exps.push_back(MI);
458    }
459    CSEPairs.clear();
460  }
461
462  return Changed;
463}
464
465/// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
466/// dominator tree node if its a leaf or all of its children are done. Walk
467/// up the dominator tree to destroy ancestors which are now done.
468void
469MachineCSE::ExitScopeIfDone(MachineDomTreeNode *Node,
470                DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
471                DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
472  if (OpenChildren[Node])
473    return;
474
475  // Pop scope.
476  ExitScope(Node->getBlock());
477
478  // Now traverse upwards to pop ancestors whose offsprings are all done.
479  while (MachineDomTreeNode *Parent = ParentMap[Node]) {
480    unsigned Left = --OpenChildren[Parent];
481    if (Left != 0)
482      break;
483    ExitScope(Parent->getBlock());
484    Node = Parent;
485  }
486}
487
488bool MachineCSE::PerformCSE(MachineDomTreeNode *Node) {
489  SmallVector<MachineDomTreeNode*, 32> Scopes;
490  SmallVector<MachineDomTreeNode*, 8> WorkList;
491  DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
492  DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
493
494  CurrVN = 0;
495
496  // Perform a DFS walk to determine the order of visit.
497  WorkList.push_back(Node);
498  do {
499    Node = WorkList.pop_back_val();
500    Scopes.push_back(Node);
501    const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
502    unsigned NumChildren = Children.size();
503    OpenChildren[Node] = NumChildren;
504    for (unsigned i = 0; i != NumChildren; ++i) {
505      MachineDomTreeNode *Child = Children[i];
506      ParentMap[Child] = Node;
507      WorkList.push_back(Child);
508    }
509  } while (!WorkList.empty());
510
511  // Now perform CSE.
512  bool Changed = false;
513  for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
514    MachineDomTreeNode *Node = Scopes[i];
515    MachineBasicBlock *MBB = Node->getBlock();
516    EnterScope(MBB);
517    Changed |= ProcessBlock(MBB);
518    // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
519    ExitScopeIfDone(Node, OpenChildren, ParentMap);
520  }
521
522  return Changed;
523}
524
525bool MachineCSE::runOnMachineFunction(MachineFunction &MF) {
526  TII = MF.getTarget().getInstrInfo();
527  TRI = MF.getTarget().getRegisterInfo();
528  MRI = &MF.getRegInfo();
529  AA = &getAnalysis<AliasAnalysis>();
530  DT = &getAnalysis<MachineDominatorTree>();
531  return PerformCSE(DT->getRootNode());
532}
533