Two fixes relating to debug value:
[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/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/MachineSSAUpdater.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/SetVector.h"
30 #include "llvm/ADT/Statistic.h"
31 using namespace llvm;
32
33 STATISTIC(NumTails     , "Number of tails duplicated");
34 STATISTIC(NumTailDups  , "Number of tail duplicated blocks");
35 STATISTIC(NumInstrDups , "Additional instructions due to tail duplication");
36 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
37 STATISTIC(NumAddedPHIs , "Number of phis added");
38
39 // Heuristic for tail duplication.
40 static cl::opt<unsigned>
41 TailDuplicateSize("tail-dup-size",
42                   cl::desc("Maximum instructions to consider tail duplicating"),
43                   cl::init(2), cl::Hidden);
44
45 static cl::opt<bool>
46 TailDupVerify("tail-dup-verify",
47               cl::desc("Verify sanity of PHI instructions during taildup"),
48               cl::init(false), cl::Hidden);
49
50 static cl::opt<unsigned>
51 TailDupLimit("tail-dup-limit", cl::init(~0U), cl::Hidden);
52
53 typedef std::vector<std::pair<MachineBasicBlock*,unsigned> > AvailableValsTy;
54
55 namespace {
56   /// TailDuplicatePass - Perform tail duplication.
57   class TailDuplicatePass : public MachineFunctionPass {
58     bool PreRegAlloc;
59     const TargetInstrInfo *TII;
60     MachineModuleInfo *MMI;
61     MachineRegisterInfo *MRI;
62
63     // SSAUpdateVRs - A list of virtual registers for which to update SSA form.
64     SmallVector<unsigned, 16> SSAUpdateVRs;
65
66     // SSAUpdateVals - For each virtual register in SSAUpdateVals keep a list of
67     // source virtual registers.
68     DenseMap<unsigned, AvailableValsTy> SSAUpdateVals;
69
70   public:
71     static char ID;
72     explicit TailDuplicatePass(bool PreRA) :
73       MachineFunctionPass(ID), PreRegAlloc(PreRA) {}
74
75     virtual bool runOnMachineFunction(MachineFunction &MF);
76     virtual const char *getPassName() const { return "Tail Duplication"; }
77
78   private:
79     void AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
80                            MachineBasicBlock *BB);
81     void ProcessPHI(MachineInstr *MI, MachineBasicBlock *TailBB,
82                     MachineBasicBlock *PredBB,
83                     DenseMap<unsigned, unsigned> &LocalVRMap,
84                     SmallVector<std::pair<unsigned,unsigned>, 4> &Copies,
85                     const DenseSet<unsigned> &UsedByPhi,
86                     bool Remove);
87     void DuplicateInstruction(MachineInstr *MI,
88                               MachineBasicBlock *TailBB,
89                               MachineBasicBlock *PredBB,
90                               MachineFunction &MF,
91                               DenseMap<unsigned, unsigned> &LocalVRMap,
92                               const DenseSet<unsigned> &UsedByPhi);
93     void UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
94                               SmallVector<MachineBasicBlock*, 8> &TDBBs,
95                               SmallSetVector<MachineBasicBlock*, 8> &Succs);
96     bool TailDuplicateBlocks(MachineFunction &MF);
97     bool shouldTailDuplicate(const MachineFunction &MF,
98                              MachineBasicBlock &TailBB);
99     bool TailDuplicate(MachineBasicBlock *TailBB, MachineFunction &MF,
100                        SmallVector<MachineBasicBlock*, 8> &TDBBs,
101                        SmallVector<MachineInstr*, 16> &Copies);
102     void RemoveDeadBlock(MachineBasicBlock *MBB);
103   };
104
105   char TailDuplicatePass::ID = 0;
106 }
107
108 FunctionPass *llvm::createTailDuplicatePass(bool PreRegAlloc) {
109   return new TailDuplicatePass(PreRegAlloc);
110 }
111
112 bool TailDuplicatePass::runOnMachineFunction(MachineFunction &MF) {
113   TII = MF.getTarget().getInstrInfo();
114   MRI = &MF.getRegInfo();
115   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
116
117   bool MadeChange = false;
118   while (TailDuplicateBlocks(MF))
119     MadeChange = true;
120
121   return MadeChange;
122 }
123
124 static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
125   for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
126     MachineBasicBlock *MBB = I;
127     SmallSetVector<MachineBasicBlock*, 8> Preds(MBB->pred_begin(),
128                                                 MBB->pred_end());
129     MachineBasicBlock::iterator MI = MBB->begin();
130     while (MI != MBB->end()) {
131       if (!MI->isPHI())
132         break;
133       for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
134              PE = Preds.end(); PI != PE; ++PI) {
135         MachineBasicBlock *PredBB = *PI;
136         bool Found = false;
137         for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
138           MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
139           if (PHIBB == PredBB) {
140             Found = true;
141             break;
142           }
143         }
144         if (!Found) {
145           dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
146           dbgs() << "  missing input from predecessor BB#"
147                  << PredBB->getNumber() << '\n';
148           llvm_unreachable(0);
149         }
150       }
151
152       for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
153         MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
154         if (CheckExtra && !Preds.count(PHIBB)) {
155           dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber()
156                  << ": " << *MI;
157           dbgs() << "  extra input from predecessor BB#"
158                  << PHIBB->getNumber() << '\n';
159           llvm_unreachable(0);
160         }
161         if (PHIBB->getNumber() < 0) {
162           dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
163           dbgs() << "  non-existing BB#" << PHIBB->getNumber() << '\n';
164           llvm_unreachable(0);
165         }
166       }
167       ++MI;
168     }
169   }
170 }
171
172 /// TailDuplicateBlocks - Look for small blocks that are unconditionally
173 /// branched to and do not fall through. Tail-duplicate their instructions
174 /// into their predecessors to eliminate (dynamic) branches.
175 bool TailDuplicatePass::TailDuplicateBlocks(MachineFunction &MF) {
176   bool MadeChange = false;
177
178   if (PreRegAlloc && TailDupVerify) {
179     DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
180     VerifyPHIs(MF, true);
181   }
182
183   SmallVector<MachineInstr*, 8> NewPHIs;
184   MachineSSAUpdater SSAUpdate(MF, &NewPHIs);
185
186   for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
187     MachineBasicBlock *MBB = I++;
188
189     if (NumTails == TailDupLimit)
190       break;
191
192     // Save the successors list.
193     SmallSetVector<MachineBasicBlock*, 8> Succs(MBB->succ_begin(),
194                                                 MBB->succ_end());
195
196     SmallVector<MachineBasicBlock*, 8> TDBBs;
197     SmallVector<MachineInstr*, 16> Copies;
198     if (TailDuplicate(MBB, MF, TDBBs, Copies)) {
199       ++NumTails;
200
201       // TailBB's immediate successors are now successors of those predecessors
202       // which duplicated TailBB. Add the predecessors as sources to the PHI
203       // instructions.
204       bool isDead = MBB->pred_empty();
205       if (PreRegAlloc)
206         UpdateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
207
208       // If it is dead, remove it.
209       if (isDead) {
210         NumInstrDups -= MBB->size();
211         RemoveDeadBlock(MBB);
212         ++NumDeadBlocks;
213       }
214
215       // Update SSA form.
216       if (!SSAUpdateVRs.empty()) {
217         for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
218           unsigned VReg = SSAUpdateVRs[i];
219           SSAUpdate.Initialize(VReg);
220
221           // If the original definition is still around, add it as an available
222           // value.
223           MachineInstr *DefMI = MRI->getVRegDef(VReg);
224           MachineBasicBlock *DefBB = 0;
225           if (DefMI) {
226             DefBB = DefMI->getParent();
227             SSAUpdate.AddAvailableValue(DefBB, VReg);
228           }
229
230           // Add the new vregs as available values.
231           DenseMap<unsigned, AvailableValsTy>::iterator LI =
232             SSAUpdateVals.find(VReg);  
233           for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
234             MachineBasicBlock *SrcBB = LI->second[j].first;
235             unsigned SrcReg = LI->second[j].second;
236             SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
237           }
238
239           // Rewrite uses that are outside of the original def's block.
240           MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
241           while (UI != MRI->use_end()) {
242             MachineOperand &UseMO = UI.getOperand();
243             MachineInstr *UseMI = &*UI;
244             ++UI;
245             if (UseMI->isDebugValue()) {
246               // SSAUpdate can replace the use with an undef. That creates
247               // a debug instruction that is a kill.
248               // FIXME: Should it SSAUpdate job to delete debug instructions
249               // instead of replacing the use with undef?
250               UseMI->eraseFromParent();
251               continue;
252             }
253             if (UseMI->getParent() == DefBB && !UseMI->isPHI())
254               continue;
255             SSAUpdate.RewriteUse(UseMO);
256           }
257         }
258
259         SSAUpdateVRs.clear();
260         SSAUpdateVals.clear();
261       }
262
263       // Eliminate some of the copies inserted by tail duplication to maintain
264       // SSA form.
265       for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
266         MachineInstr *Copy = Copies[i];
267         if (!Copy->isCopy())
268           continue;
269         unsigned Dst = Copy->getOperand(0).getReg();
270         unsigned Src = Copy->getOperand(1).getReg();
271         MachineRegisterInfo::use_iterator UI = MRI->use_begin(Src);
272         if (++UI == MRI->use_end()) {
273           // Copy is the only use. Do trivial copy propagation here.
274           MRI->replaceRegWith(Dst, Src);
275           Copy->eraseFromParent();
276         }
277       }
278
279       if (PreRegAlloc && TailDupVerify)
280         VerifyPHIs(MF, false);
281       MadeChange = true;
282     }
283   }
284   NumAddedPHIs += NewPHIs.size();
285
286   return MadeChange;
287 }
288
289 static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
290                          const MachineRegisterInfo *MRI) {
291   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
292          UE = MRI->use_end(); UI != UE; ++UI) {
293     MachineInstr *UseMI = &*UI;
294     if (UseMI->isDebugValue())
295       continue;
296     if (UseMI->getParent() != BB)
297       return true;
298   }
299   return false;
300 }
301
302 static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
303   for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
304     if (MI->getOperand(i+1).getMBB() == SrcBB)
305       return i;
306   return 0;
307 }
308
309
310 // Remember which registers are used by phis in this block. This is
311 // used to determine which registers are liveout while modifying the
312 // block (which is why we need to copy the information).
313 static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
314                               DenseSet<unsigned> *UsedByPhi) {
315   for(MachineBasicBlock::const_iterator I = BB.begin(), E = BB.end();
316       I != E; ++I) {
317     const MachineInstr &MI = *I;
318     if (!MI.isPHI())
319       break;
320     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
321       unsigned SrcReg = MI.getOperand(i).getReg();
322       UsedByPhi->insert(SrcReg);
323     }
324   }
325 }
326
327 /// AddSSAUpdateEntry - Add a definition and source virtual registers pair for
328 /// SSA update.
329 void TailDuplicatePass::AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
330                                           MachineBasicBlock *BB) {
331   DenseMap<unsigned, AvailableValsTy>::iterator LI= SSAUpdateVals.find(OrigReg);
332   if (LI != SSAUpdateVals.end())
333     LI->second.push_back(std::make_pair(BB, NewReg));
334   else {
335     AvailableValsTy Vals;
336     Vals.push_back(std::make_pair(BB, NewReg));
337     SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
338     SSAUpdateVRs.push_back(OrigReg);
339   }
340 }
341
342 /// ProcessPHI - Process PHI node in TailBB by turning it into a copy in PredBB.
343 /// Remember the source register that's contributed by PredBB and update SSA
344 /// update map.
345 void TailDuplicatePass::ProcessPHI(MachineInstr *MI,
346                                    MachineBasicBlock *TailBB,
347                                    MachineBasicBlock *PredBB,
348                                    DenseMap<unsigned, unsigned> &LocalVRMap,
349                            SmallVector<std::pair<unsigned,unsigned>, 4> &Copies,
350                                    const DenseSet<unsigned> &RegsUsedByPhi,
351                                    bool Remove) {
352   unsigned DefReg = MI->getOperand(0).getReg();
353   unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
354   assert(SrcOpIdx && "Unable to find matching PHI source?");
355   unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
356   const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
357   LocalVRMap.insert(std::make_pair(DefReg, SrcReg));
358
359   // Insert a copy from source to the end of the block. The def register is the
360   // available value liveout of the block.
361   unsigned NewDef = MRI->createVirtualRegister(RC);
362   Copies.push_back(std::make_pair(NewDef, SrcReg));
363   if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
364     AddSSAUpdateEntry(DefReg, NewDef, PredBB);
365
366   if (!Remove)
367     return;
368
369   // Remove PredBB from the PHI node.
370   MI->RemoveOperand(SrcOpIdx+1);
371   MI->RemoveOperand(SrcOpIdx);
372   if (MI->getNumOperands() == 1)
373     MI->eraseFromParent();
374 }
375
376 /// DuplicateInstruction - Duplicate a TailBB instruction to PredBB and update
377 /// the source operands due to earlier PHI translation.
378 void TailDuplicatePass::DuplicateInstruction(MachineInstr *MI,
379                                      MachineBasicBlock *TailBB,
380                                      MachineBasicBlock *PredBB,
381                                      MachineFunction &MF,
382                                      DenseMap<unsigned, unsigned> &LocalVRMap,
383                                      const DenseSet<unsigned> &UsedByPhi) {
384   MachineInstr *NewMI = TII->duplicate(MI, MF);
385   for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
386     MachineOperand &MO = NewMI->getOperand(i);
387     if (!MO.isReg())
388       continue;
389     unsigned Reg = MO.getReg();
390     if (!TargetRegisterInfo::isVirtualRegister(Reg))
391       continue;
392     if (MO.isDef()) {
393       const TargetRegisterClass *RC = MRI->getRegClass(Reg);
394       unsigned NewReg = MRI->createVirtualRegister(RC);
395       MO.setReg(NewReg);
396       LocalVRMap.insert(std::make_pair(Reg, NewReg));
397       if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
398         AddSSAUpdateEntry(Reg, NewReg, PredBB);
399     } else {
400       DenseMap<unsigned, unsigned>::iterator VI = LocalVRMap.find(Reg);
401       if (VI != LocalVRMap.end())
402         MO.setReg(VI->second);
403     }
404   }
405   PredBB->insert(PredBB->end(), NewMI);
406 }
407
408 /// UpdateSuccessorsPHIs - After FromBB is tail duplicated into its predecessor
409 /// blocks, the successors have gained new predecessors. Update the PHI
410 /// instructions in them accordingly.
411 void
412 TailDuplicatePass::UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
413                                   SmallVector<MachineBasicBlock*, 8> &TDBBs,
414                                   SmallSetVector<MachineBasicBlock*,8> &Succs) {
415   for (SmallSetVector<MachineBasicBlock*, 8>::iterator SI = Succs.begin(),
416          SE = Succs.end(); SI != SE; ++SI) {
417     MachineBasicBlock *SuccBB = *SI;
418     for (MachineBasicBlock::iterator II = SuccBB->begin(), EE = SuccBB->end();
419          II != EE; ++II) {
420       if (!II->isPHI())
421         break;
422       unsigned Idx = 0;
423       for (unsigned i = 1, e = II->getNumOperands(); i != e; i += 2) {
424         MachineOperand &MO = II->getOperand(i+1);
425         if (MO.getMBB() == FromBB) {
426           Idx = i;
427           break;
428         }
429       }
430
431       assert(Idx != 0);
432       MachineOperand &MO0 = II->getOperand(Idx);
433       unsigned Reg = MO0.getReg();
434       if (isDead) {
435         // Folded into the previous BB.
436         // There could be duplicate phi source entries. FIXME: Should sdisel
437         // or earlier pass fixed this?
438         for (unsigned i = II->getNumOperands()-2; i != Idx; i -= 2) {
439           MachineOperand &MO = II->getOperand(i+1);
440           if (MO.getMBB() == FromBB) {
441             II->RemoveOperand(i+1);
442             II->RemoveOperand(i);
443           }
444         }
445       } else
446         Idx = 0;
447
448       // If Idx is set, the operands at Idx and Idx+1 must be removed.
449       // We reuse the location to avoid expensive RemoveOperand calls.
450
451       DenseMap<unsigned,AvailableValsTy>::iterator LI=SSAUpdateVals.find(Reg);
452       if (LI != SSAUpdateVals.end()) {
453         // This register is defined in the tail block.
454         for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
455           MachineBasicBlock *SrcBB = LI->second[j].first;
456           // If we didn't duplicate a bb into a particular predecessor, we
457           // might still have added an entry to SSAUpdateVals to correcly
458           // recompute SSA. If that case, avoid adding a dummy extra argument
459           // this PHI.
460           if (!SrcBB->isSuccessor(SuccBB))
461             continue;
462
463           unsigned SrcReg = LI->second[j].second;
464           if (Idx != 0) {
465             II->getOperand(Idx).setReg(SrcReg);
466             II->getOperand(Idx+1).setMBB(SrcBB);
467             Idx = 0;
468           } else {
469             II->addOperand(MachineOperand::CreateReg(SrcReg, false));
470             II->addOperand(MachineOperand::CreateMBB(SrcBB));
471           }
472         }
473       } else {
474         // Live in tail block, must also be live in predecessors.
475         for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
476           MachineBasicBlock *SrcBB = TDBBs[j];
477           if (Idx != 0) {
478             II->getOperand(Idx).setReg(Reg);
479             II->getOperand(Idx+1).setMBB(SrcBB);
480             Idx = 0;
481           } else {
482             II->addOperand(MachineOperand::CreateReg(Reg, false));
483             II->addOperand(MachineOperand::CreateMBB(SrcBB));
484           }
485         }
486       }
487       if (Idx != 0) {
488         II->RemoveOperand(Idx+1);
489         II->RemoveOperand(Idx);
490       }
491     }
492   }
493 }
494
495 /// shouldTailDuplicate - Determine if it is profitable to duplicate this block.
496 bool
497 TailDuplicatePass::shouldTailDuplicate(const MachineFunction &MF,
498                                        MachineBasicBlock &TailBB) {
499   // Only duplicate blocks that end with unconditional branches.
500   if (TailBB.canFallThrough())
501     return false;
502
503   // Don't try to tail-duplicate single-block loops.
504   if (TailBB.isSuccessor(&TailBB))
505     return false;
506
507   // Set the limit on the cost to duplicate. When optimizing for size,
508   // duplicate only one, because one branch instruction can be eliminated to
509   // compensate for the duplication.
510   unsigned MaxDuplicateCount;
511   if (TailDuplicateSize.getNumOccurrences() == 0 &&
512       MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize))
513     MaxDuplicateCount = 1;
514   else
515     MaxDuplicateCount = TailDuplicateSize;
516
517   // If the target has hardware branch prediction that can handle indirect
518   // branches, duplicating them can often make them predictable when there
519   // are common paths through the code.  The limit needs to be high enough
520   // to allow undoing the effects of tail merging and other optimizations
521   // that rearrange the predecessors of the indirect branch.
522
523   if (PreRegAlloc && !TailBB.empty()) {
524     const TargetInstrDesc &TID = TailBB.back().getDesc();
525     if (TID.isIndirectBranch())
526       MaxDuplicateCount = 20;
527   }
528
529   // Check the instructions in the block to determine whether tail-duplication
530   // is invalid or unlikely to be profitable.
531   unsigned InstrCount = 0;
532   for (MachineBasicBlock::const_iterator I = TailBB.begin(); I != TailBB.end();
533        ++I) {
534     // Non-duplicable things shouldn't be tail-duplicated.
535     if (I->getDesc().isNotDuplicable())
536       return false;
537
538     // Do not duplicate 'return' instructions if this is a pre-regalloc run.
539     // A return may expand into a lot more instructions (e.g. reload of callee
540     // saved registers) after PEI.
541     if (PreRegAlloc && I->getDesc().isReturn())
542       return false;
543
544     // Avoid duplicating calls before register allocation. Calls presents a
545     // barrier to register allocation so duplicating them may end up increasing
546     // spills.
547     if (PreRegAlloc && I->getDesc().isCall())
548       return false;
549
550     if (!I->isPHI() && !I->isDebugValue())
551       InstrCount += 1;
552
553     if (InstrCount > MaxDuplicateCount)
554       return false;
555   }
556
557   return true;
558 }
559
560 /// TailDuplicate - If it is profitable, duplicate TailBB's contents in each
561 /// of its predecessors.
562 bool
563 TailDuplicatePass::TailDuplicate(MachineBasicBlock *TailBB, MachineFunction &MF,
564                                  SmallVector<MachineBasicBlock*, 8> &TDBBs,
565                                  SmallVector<MachineInstr*, 16> &Copies) {
566   if (!shouldTailDuplicate(MF, *TailBB))
567     return false;
568
569   DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
570
571   // Iterate through all the unique predecessors and tail-duplicate this
572   // block into them, if possible. Copying the list ahead of time also
573   // avoids trouble with the predecessor list reallocating.
574   bool Changed = false;
575   SmallSetVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
576                                               TailBB->pred_end());
577   DenseSet<unsigned> UsedByPhi;
578   getRegsUsedByPHIs(*TailBB, &UsedByPhi);
579   for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
580        PE = Preds.end(); PI != PE; ++PI) {
581     MachineBasicBlock *PredBB = *PI;
582
583     assert(TailBB != PredBB &&
584            "Single-block loop should have been rejected earlier!");
585     // EH edges are ignored by AnalyzeBranch.
586     if (PredBB->succ_size() > 1)
587       continue;
588
589     MachineBasicBlock *PredTBB, *PredFBB;
590     SmallVector<MachineOperand, 4> PredCond;
591     if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
592       continue;
593     if (!PredCond.empty())
594       continue;
595     // Don't duplicate into a fall-through predecessor (at least for now).
596     if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
597       continue;
598
599     DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
600                  << "From Succ: " << *TailBB);
601
602     TDBBs.push_back(PredBB);
603
604     // Remove PredBB's unconditional branch.
605     TII->RemoveBranch(*PredBB);
606
607     // Clone the contents of TailBB into PredBB.
608     DenseMap<unsigned, unsigned> LocalVRMap;
609     SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
610     MachineBasicBlock::iterator I = TailBB->begin();
611     while (I != TailBB->end()) {
612       MachineInstr *MI = &*I;
613       ++I;
614       if (MI->isPHI()) {
615         // Replace the uses of the def of the PHI with the register coming
616         // from PredBB.
617         ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
618       } else {
619         // Replace def of virtual registers with new registers, and update
620         // uses with PHI source register or the new registers.
621         DuplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap, UsedByPhi);
622       }
623     }
624     MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
625     for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
626       Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
627                                TII->get(TargetOpcode::COPY),
628                                CopyInfos[i].first).addReg(CopyInfos[i].second));
629     }
630
631     // Simplify
632     TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true);
633
634     NumInstrDups += TailBB->size() - 1; // subtract one for removed branch
635
636     // Update the CFG.
637     PredBB->removeSuccessor(PredBB->succ_begin());
638     assert(PredBB->succ_empty() &&
639            "TailDuplicate called on block with multiple successors!");
640     for (MachineBasicBlock::succ_iterator I = TailBB->succ_begin(),
641            E = TailBB->succ_end(); I != E; ++I)
642       PredBB->addSuccessor(*I);
643
644     Changed = true;
645     ++NumTailDups;
646   }
647
648   // If TailBB was duplicated into all its predecessors except for the prior
649   // block, which falls through unconditionally, move the contents of this
650   // block into the prior block.
651   MachineBasicBlock *PrevBB = prior(MachineFunction::iterator(TailBB));
652   MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
653   SmallVector<MachineOperand, 4> PriorCond;
654   // This has to check PrevBB->succ_size() because EH edges are ignored by
655   // AnalyzeBranch.
656   if (PrevBB->succ_size() == 1 && 
657       !TII->AnalyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) &&
658       PriorCond.empty() && !PriorTBB && TailBB->pred_size() == 1 &&
659       !TailBB->hasAddressTaken()) {
660     DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
661           << "From MBB: " << *TailBB);
662     if (PreRegAlloc) {
663       DenseMap<unsigned, unsigned> LocalVRMap;
664       SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
665       MachineBasicBlock::iterator I = TailBB->begin();
666       // Process PHI instructions first.
667       while (I != TailBB->end() && I->isPHI()) {
668         // Replace the uses of the def of the PHI with the register coming
669         // from PredBB.
670         MachineInstr *MI = &*I++;
671         ProcessPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
672         if (MI->getParent())
673           MI->eraseFromParent();
674       }
675
676       // Now copy the non-PHI instructions.
677       while (I != TailBB->end()) {
678         // Replace def of virtual registers with new registers, and update
679         // uses with PHI source register or the new registers.
680         MachineInstr *MI = &*I++;
681         DuplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap, UsedByPhi);
682         MI->eraseFromParent();
683       }
684       MachineBasicBlock::iterator Loc = PrevBB->getFirstTerminator();
685       for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
686         Copies.push_back(BuildMI(*PrevBB, Loc, DebugLoc(),
687                                  TII->get(TargetOpcode::COPY),
688                                  CopyInfos[i].first)
689                            .addReg(CopyInfos[i].second));
690       }
691     } else {
692       // No PHIs to worry about, just splice the instructions over.
693       PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
694     }
695     PrevBB->removeSuccessor(PrevBB->succ_begin());
696     assert(PrevBB->succ_empty());
697     PrevBB->transferSuccessors(TailBB);
698     TDBBs.push_back(PrevBB);
699     Changed = true;
700   }
701
702   // If this is after register allocation, there are no phis to fix.
703   if (!PreRegAlloc)
704     return Changed;
705
706   // If we made no changes so far, we are safe.
707   if (!Changed)
708     return Changed;
709
710
711   // Handle the nasty case in that we duplicated a block that is part of a loop
712   // into some but not all of its predecessors. For example:
713   //    1 -> 2 <-> 3                 |
714   //          \                      |
715   //           \---> rest            |
716   // if we duplicate 2 into 1 but not into 3, we end up with
717   // 12 -> 3 <-> 2 -> rest           |
718   //   \             /               |
719   //    \----->-----/                |
720   // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
721   // with a phi in 3 (which now dominates 2).
722   // What we do here is introduce a copy in 3 of the register defined by the
723   // phi, just like when we are duplicating 2 into 3, but we don't copy any
724   // real instructions or remove the 3 -> 2 edge from the phi in 2.
725   for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
726        PE = Preds.end(); PI != PE; ++PI) {
727     MachineBasicBlock *PredBB = *PI;
728     if (std::find(TDBBs.begin(), TDBBs.end(), PredBB) != TDBBs.end())
729       continue;
730
731     // EH edges
732     if (PredBB->succ_size() != 1)
733       continue;
734
735     DenseMap<unsigned, unsigned> LocalVRMap;
736     SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
737     MachineBasicBlock::iterator I = TailBB->begin();
738     // Process PHI instructions first.
739     while (I != TailBB->end() && I->isPHI()) {
740       // Replace the uses of the def of the PHI with the register coming
741       // from PredBB.
742       MachineInstr *MI = &*I++;
743       ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
744     }
745     MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
746     for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
747       Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
748                                TII->get(TargetOpcode::COPY),
749                                CopyInfos[i].first).addReg(CopyInfos[i].second));
750     }
751   }
752
753   return Changed;
754 }
755
756 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
757 /// function, updating the CFG.
758 void TailDuplicatePass::RemoveDeadBlock(MachineBasicBlock *MBB) {
759   assert(MBB->pred_empty() && "MBB must be dead!");
760   DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
761
762   // Remove all successors.
763   while (!MBB->succ_empty())
764     MBB->removeSuccessor(MBB->succ_end()-1);
765
766   // Remove the block.
767   MBB->eraseFromParent();
768 }