Handle recursive PHI's.
[oota-llvm.git] / lib / CodeGen / TailDuplication.cpp
1 //===-- TailDuplication.cpp - Duplicate blocks into predecessors' tails ---===//
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 duplicates basic blocks ending in unconditional branches into
11 // the tails of their predecessors.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "tailduplication"
16 #include "llvm/Function.h"
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/CodeGen/MachineModuleInfo.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/MachineSSAUpdater.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/Statistic.h"
29 using namespace llvm;
30
31 STATISTIC(NumTailDups  , "Number of tail duplicated blocks");
32 STATISTIC(NumInstrDups , "Additional instructions due to tail duplication");
33 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
34
35 // Heuristic for tail duplication.
36 static cl::opt<unsigned>
37 TailDuplicateSize("tail-dup-size",
38                   cl::desc("Maximum instructions to consider tail duplicating"),
39                   cl::init(2), cl::Hidden);
40
41 typedef std::vector<std::pair<MachineBasicBlock*,unsigned> > AvailableValsTy;
42
43 namespace {
44   /// TailDuplicatePass - Perform tail duplication.
45   class TailDuplicatePass : public MachineFunctionPass {
46     bool PreRegAlloc;
47     const TargetInstrInfo *TII;
48     MachineModuleInfo *MMI;
49     MachineRegisterInfo *MRI;
50
51     // SSAUpdateVRs - A list of virtual registers for which to update SSA form.
52     SmallVector<unsigned, 16> SSAUpdateVRs;
53
54     // SSAUpdateVals - For each virtual register in SSAUpdateVals keep a list of
55     // source virtual registers.
56     DenseMap<unsigned, AvailableValsTy> SSAUpdateVals;
57
58   public:
59     static char ID;
60     explicit TailDuplicatePass(bool PreRA) :
61       MachineFunctionPass(&ID), PreRegAlloc(PreRA) {}
62
63     virtual bool runOnMachineFunction(MachineFunction &MF);
64     virtual const char *getPassName() const { return "Tail Duplication"; }
65
66   private:
67     void AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
68                            MachineBasicBlock *BB);
69     void ProcessPHI(MachineInstr *MI, MachineBasicBlock *TailBB,
70                     MachineBasicBlock *PredBB,
71                     DenseMap<unsigned, unsigned> &LocalVRMap);
72     void DuplicateInstruction(MachineInstr *MI,
73                               MachineBasicBlock *TailBB,
74                               MachineBasicBlock *PredBB,
75                               MachineFunction &MF,
76                               DenseMap<unsigned, unsigned> &LocalVRMap);
77     void UpdateSuccessorsPHIs(MachineBasicBlock *FromBB,MachineBasicBlock *ToBB,
78                               SmallSetVector<MachineBasicBlock*,8> &Succs);
79     bool TailDuplicateBlocks(MachineFunction &MF);
80     bool TailDuplicate(MachineBasicBlock *TailBB, MachineFunction &MF);
81     void RemoveDeadBlock(MachineBasicBlock *MBB);
82   };
83
84   char TailDuplicatePass::ID = 0;
85 }
86
87 FunctionPass *llvm::createTailDuplicatePass(bool PreRegAlloc) {
88   return new TailDuplicatePass(PreRegAlloc);
89 }
90
91 bool TailDuplicatePass::runOnMachineFunction(MachineFunction &MF) {
92   TII = MF.getTarget().getInstrInfo();
93   MRI = &MF.getRegInfo();
94   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
95
96   bool MadeChange = false;
97   bool MadeChangeThisIteration = true;
98   while (MadeChangeThisIteration) {
99     MadeChangeThisIteration = false;
100     MadeChangeThisIteration |= TailDuplicateBlocks(MF);
101     MadeChange |= MadeChangeThisIteration;
102   }
103
104   return MadeChange;
105 }
106
107 /// TailDuplicateBlocks - Look for small blocks that are unconditionally
108 /// branched to and do not fall through. Tail-duplicate their instructions
109 /// into their predecessors to eliminate (dynamic) branches.
110 bool TailDuplicatePass::TailDuplicateBlocks(MachineFunction &MF) {
111   bool MadeChange = false;
112
113   for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
114     MachineBasicBlock *MBB = I++;
115
116     // Only duplicate blocks that end with unconditional branches.
117     if (MBB->canFallThrough())
118       continue;
119
120     MadeChange |= TailDuplicate(MBB, MF);
121
122     // If it is dead, remove it. Don't do this if this pass is run before
123     // register allocation to avoid having to update PHI nodes.
124     if (!PreRegAlloc && MBB->pred_empty()) {
125       NumInstrDups -= MBB->size();
126       RemoveDeadBlock(MBB);
127       MadeChange = true;
128       ++NumDeadBlocks;
129     }
130   }
131
132   return MadeChange;
133 }
134
135 static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
136                          const MachineRegisterInfo *MRI) {
137   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
138          UE = MRI->use_end(); UI != UE; ++UI) {
139     MachineInstr *UseMI = &*UI;
140     if (UseMI->getParent() != BB)
141       return true;
142   }
143   return false;
144 }
145
146 static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
147   for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
148     if (MI->getOperand(i+1).getMBB() == SrcBB)
149       return i;
150   return 0;
151 }
152
153 /// AddSSAUpdateEntry - Add a definition and source virtual registers pair for
154 /// SSA update.
155 void TailDuplicatePass::AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
156                                           MachineBasicBlock *BB) {
157   DenseMap<unsigned, AvailableValsTy>::iterator LI= SSAUpdateVals.find(OrigReg);
158   if (LI != SSAUpdateVals.end())
159     LI->second.push_back(std::make_pair(BB, NewReg));
160   else {
161     AvailableValsTy Vals;
162     Vals.push_back(std::make_pair(BB, NewReg));
163     SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
164     SSAUpdateVRs.push_back(OrigReg);
165   }
166 }
167
168 /// ProcessPHI - Process but do not duplicate a PHI node in TailBB. Remember the
169 /// source register that's contributed by PredBB and update SSA update map.
170 void TailDuplicatePass::ProcessPHI(MachineInstr *MI,
171                                    MachineBasicBlock *TailBB,
172                                    MachineBasicBlock *PredBB,
173                                    DenseMap<unsigned, unsigned> &LocalVRMap) {
174   unsigned DefReg = MI->getOperand(0).getReg();
175   unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
176   assert(SrcOpIdx && "Unable to find matching PHI source?");
177   unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
178   LocalVRMap.insert(std::make_pair(DefReg, SrcReg));
179   if (isDefLiveOut(DefReg, TailBB, MRI))
180     AddSSAUpdateEntry(DefReg, SrcReg, PredBB);
181
182   // Remove PredBB from the PHI node.
183   MI->RemoveOperand(SrcOpIdx+1);
184   MI->RemoveOperand(SrcOpIdx);
185   if (MI->getNumOperands() == 1)
186     MI->eraseFromParent();
187 }
188
189 /// DuplicateInstruction - Duplicate a TailBB instruction to PredBB and update
190 /// the source operands due to earlier PHI translation.
191 void TailDuplicatePass::DuplicateInstruction(MachineInstr *MI,
192                                      MachineBasicBlock *TailBB,
193                                      MachineBasicBlock *PredBB,
194                                      MachineFunction &MF,
195                                      DenseMap<unsigned, unsigned> &LocalVRMap) {
196   MachineInstr *NewMI = MF.CloneMachineInstr(MI);
197   for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
198     MachineOperand &MO = NewMI->getOperand(i);
199     if (!MO.isReg())
200       continue;
201     unsigned Reg = MO.getReg();
202     if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
203       continue;
204     if (MO.isDef()) {
205       const TargetRegisterClass *RC = MRI->getRegClass(Reg);
206       unsigned NewReg = MRI->createVirtualRegister(RC);
207       MO.setReg(NewReg);
208       LocalVRMap.insert(std::make_pair(Reg, NewReg));
209       if (isDefLiveOut(Reg, TailBB, MRI))
210         AddSSAUpdateEntry(Reg, NewReg, PredBB);
211     } else {
212       DenseMap<unsigned, unsigned>::iterator VI = LocalVRMap.find(Reg);
213       if (VI != LocalVRMap.end())
214         MO.setReg(VI->second);
215     }
216   }
217   PredBB->insert(PredBB->end(), NewMI);
218 }
219
220 /// UpdateSuccessorsPHIs - After FromBB is tail duplicated into its predecessor
221 /// blocks, the successors have gained new predecessors. Update the PHI
222 /// instructions in them accordingly.
223 void TailDuplicatePass::UpdateSuccessorsPHIs(MachineBasicBlock *FromBB,
224                                   MachineBasicBlock *ToBB,
225                                   SmallSetVector<MachineBasicBlock*,8> &Succs) {
226   for (SmallSetVector<MachineBasicBlock*, 8>::iterator SI = Succs.begin(),
227          SE = Succs.end(); SI != SE; ++SI) {
228     MachineBasicBlock *SuccBB = *SI;
229     for (MachineBasicBlock::iterator II = SuccBB->begin(), EE = SuccBB->end();
230          II != EE; ++II) {
231       if (II->getOpcode() != TargetInstrInfo::PHI)
232         break;
233       for (unsigned i = 1, e = II->getNumOperands(); i != e; i += 2) {
234         MachineOperand &MO1 = II->getOperand(i+1);
235         if (MO1.getMBB() != FromBB)
236           continue;
237         MachineOperand &MO0 = II->getOperand(i);
238         unsigned Reg = MO0.getReg();
239         if (ToBB) {
240           // Folded into the previous BB.
241           II->RemoveOperand(i+1);
242           II->RemoveOperand(i);
243         }
244         DenseMap<unsigned,AvailableValsTy>::iterator LI=SSAUpdateVals.find(Reg);
245         if (LI == SSAUpdateVals.end())
246           break;
247         for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
248           MachineBasicBlock *SrcBB = LI->second[j].first;
249           unsigned SrcReg = LI->second[j].second;
250           II->addOperand(MachineOperand::CreateReg(SrcReg, false));
251           II->addOperand(MachineOperand::CreateMBB(SrcBB));
252         }
253         break;
254       }
255     }
256   }
257 }
258
259 /// TailDuplicate - If it is profitable, duplicate TailBB's contents in each
260 /// of its predecessors.
261 bool TailDuplicatePass::TailDuplicate(MachineBasicBlock *TailBB,
262                                       MachineFunction &MF) {
263   // Don't try to tail-duplicate single-block loops.
264   if (TailBB->isSuccessor(TailBB))
265     return false;
266
267   // Set the limit on the number of instructions to duplicate, with a default
268   // of one less than the tail-merge threshold. When optimizing for size,
269   // duplicate only one, because one branch instruction can be eliminated to
270   // compensate for the duplication.
271   unsigned MaxDuplicateCount;
272   if (!TailBB->empty() && TailBB->back().getDesc().isIndirectBranch())
273     // If the target has hardware branch prediction that can handle indirect
274     // branches, duplicating them can often make them predictable when there
275     // are common paths through the code.  The limit needs to be high enough
276     // to allow undoing the effects of tail merging.
277     MaxDuplicateCount = 20;
278   else if (MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize))
279     MaxDuplicateCount = 1;
280   else
281     MaxDuplicateCount = TailDuplicateSize;
282
283   // Check the instructions in the block to determine whether tail-duplication
284   // is invalid or unlikely to be profitable.
285   unsigned InstrCount = 0;
286   bool HasCall = false;
287   for (MachineBasicBlock::iterator I = TailBB->begin();
288        I != TailBB->end(); ++I) {
289     // Non-duplicable things shouldn't be tail-duplicated.
290     if (I->getDesc().isNotDuplicable()) return false;
291     // Do not duplicate 'return' instructions if this is a pre-regalloc run.
292     // A return may expand into a lot more instructions (e.g. reload of callee
293     // saved registers) after PEI.
294     if (PreRegAlloc && I->getDesc().isReturn()) return false;
295     // Don't duplicate more than the threshold.
296     if (InstrCount == MaxDuplicateCount) return false;
297     // Remember if we saw a call.
298     if (I->getDesc().isCall()) HasCall = true;
299     if (I->getOpcode() != TargetInstrInfo::PHI)
300       InstrCount += 1;
301   }
302   // Heuristically, don't tail-duplicate calls if it would expand code size,
303   // as it's less likely to be worth the extra cost.
304   if (InstrCount > 1 && HasCall)
305     return false;
306
307   // Iterate through all the unique predecessors and tail-duplicate this
308   // block into them, if possible. Copying the list ahead of time also
309   // avoids trouble with the predecessor list reallocating.
310   bool Changed = false;
311   SmallSetVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
312                                               TailBB->pred_end());
313   for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
314        PE = Preds.end(); PI != PE; ++PI) {
315     MachineBasicBlock *PredBB = *PI;
316
317     assert(TailBB != PredBB &&
318            "Single-block loop should have been rejected earlier!");
319     if (PredBB->succ_size() > 1) continue;
320
321     MachineBasicBlock *PredTBB, *PredFBB;
322     SmallVector<MachineOperand, 4> PredCond;
323     if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
324       continue;
325     if (!PredCond.empty())
326       continue;
327     // EH edges are ignored by AnalyzeBranch.
328     if (PredBB->succ_size() != 1)
329       continue;
330     // Don't duplicate into a fall-through predecessor (at least for now).
331     if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
332       continue;
333
334     DEBUG(errs() << "\nTail-duplicating into PredBB: " << *PredBB
335                  << "From Succ: " << *TailBB);
336
337     // Remove PredBB's unconditional branch.
338     TII->RemoveBranch(*PredBB);
339
340     // Clone the contents of TailBB into PredBB.
341     DenseMap<unsigned, unsigned> LocalVRMap;
342     MachineBasicBlock::iterator I = TailBB->begin();
343     while (I != TailBB->end()) {
344       MachineInstr *MI = &*I;
345       ++I;
346       if (MI->getOpcode() == TargetInstrInfo::PHI) {
347         // Replace the uses of the def of the PHI with the register coming
348         // from PredBB.
349         ProcessPHI(MI, TailBB, PredBB, LocalVRMap);
350       } else {
351         // Replace def of virtual registers with new registers, and update
352         // uses with PHI source register or the new registers.
353         DuplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap);
354       }
355     }
356     NumInstrDups += TailBB->size() - 1; // subtract one for removed branch
357
358     // Update the CFG.
359     PredBB->removeSuccessor(PredBB->succ_begin());
360     assert(PredBB->succ_empty() &&
361            "TailDuplicate called on block with multiple successors!");
362     for (MachineBasicBlock::succ_iterator I = TailBB->succ_begin(),
363            E = TailBB->succ_end(); I != E; ++I)
364       PredBB->addSuccessor(*I);
365
366     Changed = true;
367     ++NumTailDups;
368   }
369
370   // Save the successors list.
371   SmallSetVector<MachineBasicBlock*, 8> Succs(TailBB->succ_begin(),
372                                               TailBB->succ_end());
373
374   // If TailBB was duplicated into all its predecessors except for the prior
375   // block, which falls through unconditionally, move the contents of this
376   // block into the prior block.
377   MachineBasicBlock *PrevBB = prior(MachineFunction::iterator(TailBB));
378   MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
379   SmallVector<MachineOperand, 4> PriorCond;
380   bool PriorUnAnalyzable =
381     TII->AnalyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true);
382   // This has to check PrevBB->succ_size() because EH edges are ignored by
383   // AnalyzeBranch.
384   // If TailBB starts with PHIs, then don't bother. Let the post regalloc
385   // run clean it up.
386   MachineBasicBlock *NewTailBB = 0;
387   if (!PriorUnAnalyzable && PriorCond.empty() && !PriorTBB &&
388       TailBB->pred_size() == 1 && PrevBB->succ_size() == 1 &&
389       !TailBB->hasAddressTaken()) {
390     DEBUG(errs() << "\nMerging into block: " << *PrevBB
391           << "From MBB: " << *TailBB);
392     if (PreRegAlloc) {
393       DenseMap<unsigned, unsigned> LocalVRMap;
394       MachineBasicBlock::iterator I = TailBB->begin();
395       // Process PHI instructions first.
396       while (I != TailBB->end() && I->getOpcode() == TargetInstrInfo::PHI) {
397         // Replace the uses of the def of the PHI with the register coming
398         // from PredBB.
399         MachineInstr *MI = &*I++;
400         ProcessPHI(MI, TailBB, PrevBB, LocalVRMap);
401         if (MI->getParent())
402           MI->eraseFromParent();
403       }
404
405       // Now copy the non-PHI instructions.
406       while (I != TailBB->end()) {
407         // Replace def of virtual registers with new registers, and update
408         // uses with PHI source register or the new registers.
409         MachineInstr *MI = &*I++;
410         DuplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap);
411         MI->eraseFromParent();
412       }
413     } else {
414       // No PHIs to worry about, just splice the instructions over.
415       PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
416     }
417     PrevBB->removeSuccessor(PrevBB->succ_begin());
418     assert(PrevBB->succ_empty());
419     PrevBB->transferSuccessors(TailBB);
420     NewTailBB = PrevBB;
421     Changed = true;
422   }
423
424   if (!PreRegAlloc)
425     return Changed;
426
427   // TailBB's immediate successors are now successors of those predecessors
428   // which duplicated TailBB. Add the predecessors as sources to the PHI
429   // instructions.
430   UpdateSuccessorsPHIs(TailBB, NewTailBB, Succs);
431
432   if (!SSAUpdateVRs.empty()) {
433     // Update SSA form.
434     MachineSSAUpdater SSAUpdate(MF);
435     for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
436       unsigned VReg = SSAUpdateVRs[i];
437       SSAUpdate.Initialize(VReg);
438
439       // If the original definition is still around, add it as an available
440       // value.
441       MachineInstr *DefMI = MRI->getVRegDef(VReg);
442       MachineBasicBlock *DefBB = 0;
443       if (DefMI) {
444         DefBB = DefMI->getParent();
445         SSAUpdate.AddAvailableValue(DefBB, VReg);
446       }
447
448       // Add the new vregs as available values.
449       DenseMap<unsigned, AvailableValsTy>::iterator LI =
450         SSAUpdateVals.find(VReg);  
451       for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
452         MachineBasicBlock *SrcBB = LI->second[j].first;
453         unsigned SrcReg = LI->second[j].second;
454         SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
455       }
456
457       // Rewrite uses that are outside of the original def's block.
458       MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
459       while (UI != MRI->use_end()) {
460         MachineOperand &UseMO = UI.getOperand();
461         MachineInstr *UseMI = &*UI;
462         ++UI;
463         if (UseMI->getParent() != DefBB)
464           SSAUpdate.RewriteUse(UseMO);
465       }
466     }
467
468     SSAUpdateVRs.clear();
469     SSAUpdateVals.clear();
470   }
471
472   return Changed;
473 }
474
475 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
476 /// function, updating the CFG.
477 void TailDuplicatePass::RemoveDeadBlock(MachineBasicBlock *MBB) {
478   assert(MBB->pred_empty() && "MBB must be dead!");
479   DEBUG(errs() << "\nRemoving MBB: " << *MBB);
480
481   // Remove all successors.
482   while (!MBB->succ_empty())
483     MBB->removeSuccessor(MBB->succ_end()-1);
484
485   // If there are any labels in the basic block, unregister them from
486   // MachineModuleInfo.
487   if (MMI && !MBB->empty()) {
488     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
489          I != E; ++I) {
490       if (I->isLabel())
491         // The label ID # is always operand #0, an immediate.
492         MMI->InvalidateLabel(I->getOperand(0).getImm());
493     }
494   }
495
496   // Remove the block.
497   MBB->eraseFromParent();
498 }
499