blob: 3111d5931f1ab041db58d25032da20b9b0e1bf21 [file] [log] [blame]
Bob Wilson15acadd2009-11-26 00:32:21 +00001//===-- 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"
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +000020#include "llvm/CodeGen/MachineInstrBuilder.h"
Evan Cheng111e7622009-12-03 08:43:53 +000021#include "llvm/CodeGen/MachineRegisterInfo.h"
22#include "llvm/CodeGen/MachineSSAUpdater.h"
Bob Wilson15acadd2009-11-26 00:32:21 +000023#include "llvm/Target/TargetInstrInfo.h"
24#include "llvm/Support/CommandLine.h"
25#include "llvm/Support/Debug.h"
Evan Cheng75eb5352009-12-07 10:15:19 +000026#include "llvm/Support/ErrorHandling.h"
Bob Wilson15acadd2009-11-26 00:32:21 +000027#include "llvm/Support/raw_ostream.h"
28#include "llvm/ADT/SmallSet.h"
29#include "llvm/ADT/SetVector.h"
30#include "llvm/ADT/Statistic.h"
31using namespace llvm;
32
Evan Cheng75eb5352009-12-07 10:15:19 +000033STATISTIC(NumTails , "Number of tails duplicated");
Bob Wilson15acadd2009-11-26 00:32:21 +000034STATISTIC(NumTailDups , "Number of tail duplicated blocks");
35STATISTIC(NumInstrDups , "Additional instructions due to tail duplication");
36STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
Rafael Espindola0cdca082011-06-08 14:13:31 +000037STATISTIC(NumAddedPHIs , "Number of phis added");
Bob Wilson15acadd2009-11-26 00:32:21 +000038
39// Heuristic for tail duplication.
40static cl::opt<unsigned>
41TailDuplicateSize("tail-dup-size",
42 cl::desc("Maximum instructions to consider tail duplicating"),
43 cl::init(2), cl::Hidden);
44
Evan Cheng75eb5352009-12-07 10:15:19 +000045static cl::opt<bool>
46TailDupVerify("tail-dup-verify",
47 cl::desc("Verify sanity of PHI instructions during taildup"),
48 cl::init(false), cl::Hidden);
49
50static cl::opt<unsigned>
51TailDupLimit("tail-dup-limit", cl::init(~0U), cl::Hidden);
52
Evan Cheng11572ba2009-12-04 19:09:10 +000053typedef std::vector<std::pair<MachineBasicBlock*,unsigned> > AvailableValsTy;
Evan Cheng111e7622009-12-03 08:43:53 +000054
Bob Wilson15acadd2009-11-26 00:32:21 +000055namespace {
Bob Wilson2d521e52009-11-26 21:38:41 +000056 /// TailDuplicatePass - Perform tail duplication.
57 class TailDuplicatePass : public MachineFunctionPass {
Evan Cheng79fc6f42009-12-04 09:42:45 +000058 bool PreRegAlloc;
Bob Wilson15acadd2009-11-26 00:32:21 +000059 const TargetInstrInfo *TII;
60 MachineModuleInfo *MMI;
Evan Cheng111e7622009-12-03 08:43:53 +000061 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;
Bob Wilson15acadd2009-11-26 00:32:21 +000069
70 public:
71 static char ID;
Evan Cheng79fc6f42009-12-04 09:42:45 +000072 explicit TailDuplicatePass(bool PreRA) :
Owen Anderson90c579d2010-08-06 18:33:48 +000073 MachineFunctionPass(ID), PreRegAlloc(PreRA) {}
Bob Wilson15acadd2009-11-26 00:32:21 +000074
75 virtual bool runOnMachineFunction(MachineFunction &MF);
76 virtual const char *getPassName() const { return "Tail Duplication"; }
77
78 private:
Evan Cheng11572ba2009-12-04 19:09:10 +000079 void AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
80 MachineBasicBlock *BB);
Evan Cheng79fc6f42009-12-04 09:42:45 +000081 void ProcessPHI(MachineInstr *MI, MachineBasicBlock *TailBB,
82 MachineBasicBlock *PredBB,
Evan Cheng75eb5352009-12-07 10:15:19 +000083 DenseMap<unsigned, unsigned> &LocalVRMap,
Rafael Espindola0f28c3f2011-06-09 22:53:47 +000084 SmallVector<std::pair<unsigned,unsigned>, 4> &Copies,
Rafael Espindola689d7d52011-06-09 23:22:56 +000085 const DenseSet<unsigned> &UsedByPhi,
86 bool Remove);
Evan Cheng79fc6f42009-12-04 09:42:45 +000087 void DuplicateInstruction(MachineInstr *MI,
88 MachineBasicBlock *TailBB,
89 MachineBasicBlock *PredBB,
90 MachineFunction &MF,
Rafael Espindola0f28c3f2011-06-09 22:53:47 +000091 DenseMap<unsigned, unsigned> &LocalVRMap,
92 const DenseSet<unsigned> &UsedByPhi);
Evan Cheng75eb5352009-12-07 10:15:19 +000093 void UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
94 SmallVector<MachineBasicBlock*, 8> &TDBBs,
95 SmallSetVector<MachineBasicBlock*, 8> &Succs);
Bob Wilson15acadd2009-11-26 00:32:21 +000096 bool TailDuplicateBlocks(MachineFunction &MF);
Rafael Espindola54c25622011-06-09 19:54:42 +000097 bool shouldTailDuplicate(const MachineFunction &MF,
Rafael Espindola9dbbd872011-06-23 03:41:29 +000098 bool IsSimple, MachineBasicBlock &TailBB);
Rafael Espindola275c1f92011-06-20 04:16:35 +000099 bool isSimpleBB(MachineBasicBlock *TailBB);
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000100 bool canCompletelyDuplicateBB(MachineBasicBlock &BB, bool IsSimple);
101 void duplicateSimpleBB(MachineBasicBlock *TailBB,
Rafael Espindola275c1f92011-06-20 04:16:35 +0000102 SmallVector<MachineBasicBlock*, 8> &TDBBs,
103 const DenseSet<unsigned> &RegsUsedByPhi,
104 SmallVector<MachineInstr*, 16> &Copies);
Evan Cheng75eb5352009-12-07 10:15:19 +0000105 bool TailDuplicate(MachineBasicBlock *TailBB, MachineFunction &MF,
Evan Cheng3466f132009-12-15 01:44:10 +0000106 SmallVector<MachineBasicBlock*, 8> &TDBBs,
107 SmallVector<MachineInstr*, 16> &Copies);
Bob Wilson15acadd2009-11-26 00:32:21 +0000108 void RemoveDeadBlock(MachineBasicBlock *MBB);
109 };
110
Bob Wilson2d521e52009-11-26 21:38:41 +0000111 char TailDuplicatePass::ID = 0;
Bob Wilson15acadd2009-11-26 00:32:21 +0000112}
113
Evan Cheng79fc6f42009-12-04 09:42:45 +0000114FunctionPass *llvm::createTailDuplicatePass(bool PreRegAlloc) {
115 return new TailDuplicatePass(PreRegAlloc);
Bob Wilson15acadd2009-11-26 00:32:21 +0000116}
117
Bob Wilson2d521e52009-11-26 21:38:41 +0000118bool TailDuplicatePass::runOnMachineFunction(MachineFunction &MF) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000119 TII = MF.getTarget().getInstrInfo();
Evan Cheng111e7622009-12-03 08:43:53 +0000120 MRI = &MF.getRegInfo();
Bob Wilson15acadd2009-11-26 00:32:21 +0000121 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
122
123 bool MadeChange = false;
Jakob Stoklund Olesen057d5392010-01-15 19:59:57 +0000124 while (TailDuplicateBlocks(MF))
125 MadeChange = true;
Bob Wilson15acadd2009-11-26 00:32:21 +0000126
127 return MadeChange;
128}
129
Evan Cheng75eb5352009-12-07 10:15:19 +0000130static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
131 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
132 MachineBasicBlock *MBB = I;
133 SmallSetVector<MachineBasicBlock*, 8> Preds(MBB->pred_begin(),
134 MBB->pred_end());
135 MachineBasicBlock::iterator MI = MBB->begin();
136 while (MI != MBB->end()) {
Chris Lattner518bb532010-02-09 19:54:29 +0000137 if (!MI->isPHI())
Evan Cheng75eb5352009-12-07 10:15:19 +0000138 break;
139 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
140 PE = Preds.end(); PI != PE; ++PI) {
141 MachineBasicBlock *PredBB = *PI;
142 bool Found = false;
143 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
144 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
145 if (PHIBB == PredBB) {
146 Found = true;
147 break;
148 }
149 }
150 if (!Found) {
David Greene00dec1b2010-01-05 01:25:15 +0000151 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
152 dbgs() << " missing input from predecessor BB#"
Evan Cheng75eb5352009-12-07 10:15:19 +0000153 << PredBB->getNumber() << '\n';
154 llvm_unreachable(0);
155 }
156 }
157
158 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
159 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
160 if (CheckExtra && !Preds.count(PHIBB)) {
David Greene00dec1b2010-01-05 01:25:15 +0000161 dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber()
Evan Cheng75eb5352009-12-07 10:15:19 +0000162 << ": " << *MI;
David Greene00dec1b2010-01-05 01:25:15 +0000163 dbgs() << " extra input from predecessor BB#"
Evan Cheng75eb5352009-12-07 10:15:19 +0000164 << PHIBB->getNumber() << '\n';
Rafael Espindolad3f4eea2011-06-09 23:55:56 +0000165 llvm_unreachable(0);
Evan Cheng75eb5352009-12-07 10:15:19 +0000166 }
167 if (PHIBB->getNumber() < 0) {
David Greene00dec1b2010-01-05 01:25:15 +0000168 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
169 dbgs() << " non-existing BB#" << PHIBB->getNumber() << '\n';
Evan Cheng75eb5352009-12-07 10:15:19 +0000170 llvm_unreachable(0);
171 }
172 }
173 ++MI;
174 }
175 }
176}
177
Bob Wilson15acadd2009-11-26 00:32:21 +0000178/// TailDuplicateBlocks - Look for small blocks that are unconditionally
179/// branched to and do not fall through. Tail-duplicate their instructions
180/// into their predecessors to eliminate (dynamic) branches.
Bob Wilson2d521e52009-11-26 21:38:41 +0000181bool TailDuplicatePass::TailDuplicateBlocks(MachineFunction &MF) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000182 bool MadeChange = false;
183
Evan Cheng75eb5352009-12-07 10:15:19 +0000184 if (PreRegAlloc && TailDupVerify) {
David Greene00dec1b2010-01-05 01:25:15 +0000185 DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
Evan Cheng75eb5352009-12-07 10:15:19 +0000186 VerifyPHIs(MF, true);
187 }
188
189 SmallVector<MachineInstr*, 8> NewPHIs;
190 MachineSSAUpdater SSAUpdate(MF, &NewPHIs);
191
Bob Wilson15acadd2009-11-26 00:32:21 +0000192 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
193 MachineBasicBlock *MBB = I++;
194
Evan Cheng75eb5352009-12-07 10:15:19 +0000195 if (NumTails == TailDupLimit)
196 break;
197
Evan Cheng75eb5352009-12-07 10:15:19 +0000198 // Save the successors list.
199 SmallSetVector<MachineBasicBlock*, 8> Succs(MBB->succ_begin(),
200 MBB->succ_end());
Bob Wilson15acadd2009-11-26 00:32:21 +0000201
Evan Cheng75eb5352009-12-07 10:15:19 +0000202 SmallVector<MachineBasicBlock*, 8> TDBBs;
Evan Cheng3466f132009-12-15 01:44:10 +0000203 SmallVector<MachineInstr*, 16> Copies;
204 if (TailDuplicate(MBB, MF, TDBBs, Copies)) {
Evan Cheng75eb5352009-12-07 10:15:19 +0000205 ++NumTails;
206
207 // TailBB's immediate successors are now successors of those predecessors
208 // which duplicated TailBB. Add the predecessors as sources to the PHI
209 // instructions.
Rafael Espindolad6379a92011-06-22 22:31:57 +0000210 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
Evan Cheng75eb5352009-12-07 10:15:19 +0000211 if (PreRegAlloc)
212 UpdateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
213
214 // If it is dead, remove it.
215 if (isDead) {
216 NumInstrDups -= MBB->size();
217 RemoveDeadBlock(MBB);
218 ++NumDeadBlocks;
219 }
220
221 // Update SSA form.
222 if (!SSAUpdateVRs.empty()) {
223 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
224 unsigned VReg = SSAUpdateVRs[i];
225 SSAUpdate.Initialize(VReg);
226
227 // If the original definition is still around, add it as an available
228 // value.
229 MachineInstr *DefMI = MRI->getVRegDef(VReg);
230 MachineBasicBlock *DefBB = 0;
231 if (DefMI) {
232 DefBB = DefMI->getParent();
233 SSAUpdate.AddAvailableValue(DefBB, VReg);
234 }
235
236 // Add the new vregs as available values.
237 DenseMap<unsigned, AvailableValsTy>::iterator LI =
238 SSAUpdateVals.find(VReg);
239 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
240 MachineBasicBlock *SrcBB = LI->second[j].first;
241 unsigned SrcReg = LI->second[j].second;
242 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
243 }
244
245 // Rewrite uses that are outside of the original def's block.
246 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
247 while (UI != MRI->use_end()) {
248 MachineOperand &UseMO = UI.getOperand();
249 MachineInstr *UseMI = &*UI;
250 ++UI;
Rafael Espindoladb3983b2011-06-17 13:59:43 +0000251 if (UseMI->isDebugValue()) {
252 // SSAUpdate can replace the use with an undef. That creates
253 // a debug instruction that is a kill.
254 // FIXME: Should it SSAUpdate job to delete debug instructions
255 // instead of replacing the use with undef?
256 UseMI->eraseFromParent();
257 continue;
258 }
Rafael Espindolac2e9a502011-06-09 20:55:41 +0000259 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
Evan Cheng75eb5352009-12-07 10:15:19 +0000260 continue;
261 SSAUpdate.RewriteUse(UseMO);
Evan Cheng75eb5352009-12-07 10:15:19 +0000262 }
263 }
264
265 SSAUpdateVRs.clear();
266 SSAUpdateVals.clear();
267 }
268
Bob Wilsonbfdcf3b2010-01-15 06:29:17 +0000269 // Eliminate some of the copies inserted by tail duplication to maintain
Evan Cheng3466f132009-12-15 01:44:10 +0000270 // SSA form.
271 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
272 MachineInstr *Copy = Copies[i];
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000273 if (!Copy->isCopy())
274 continue;
275 unsigned Dst = Copy->getOperand(0).getReg();
276 unsigned Src = Copy->getOperand(1).getReg();
277 MachineRegisterInfo::use_iterator UI = MRI->use_begin(Src);
278 if (++UI == MRI->use_end()) {
279 // Copy is the only use. Do trivial copy propagation here.
280 MRI->replaceRegWith(Dst, Src);
281 Copy->eraseFromParent();
Evan Cheng3466f132009-12-15 01:44:10 +0000282 }
283 }
284
Evan Cheng75eb5352009-12-07 10:15:19 +0000285 if (PreRegAlloc && TailDupVerify)
286 VerifyPHIs(MF, false);
Bob Wilson15acadd2009-11-26 00:32:21 +0000287 MadeChange = true;
Bob Wilson15acadd2009-11-26 00:32:21 +0000288 }
289 }
Rafael Espindolad69f85e2011-06-08 14:23:19 +0000290 NumAddedPHIs += NewPHIs.size();
Evan Cheng111e7622009-12-03 08:43:53 +0000291
Bob Wilson15acadd2009-11-26 00:32:21 +0000292 return MadeChange;
293}
294
Evan Cheng111e7622009-12-03 08:43:53 +0000295static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
296 const MachineRegisterInfo *MRI) {
297 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
298 UE = MRI->use_end(); UI != UE; ++UI) {
299 MachineInstr *UseMI = &*UI;
Rafael Espindoladb3983b2011-06-17 13:59:43 +0000300 if (UseMI->isDebugValue())
301 continue;
Evan Cheng111e7622009-12-03 08:43:53 +0000302 if (UseMI->getParent() != BB)
303 return true;
304 }
305 return false;
306}
307
308static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
309 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
310 if (MI->getOperand(i+1).getMBB() == SrcBB)
311 return i;
312 return 0;
313}
314
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000315
316// Remember which registers are used by phis in this block. This is
317// used to determine which registers are liveout while modifying the
318// block (which is why we need to copy the information).
319static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
Rafael Espindola33b46582011-06-10 21:01:53 +0000320 DenseSet<unsigned> *UsedByPhi) {
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000321 for(MachineBasicBlock::const_iterator I = BB.begin(), E = BB.end();
322 I != E; ++I) {
323 const MachineInstr &MI = *I;
324 if (!MI.isPHI())
325 break;
326 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
327 unsigned SrcReg = MI.getOperand(i).getReg();
328 UsedByPhi->insert(SrcReg);
329 }
330 }
331}
332
Evan Cheng111e7622009-12-03 08:43:53 +0000333/// AddSSAUpdateEntry - Add a definition and source virtual registers pair for
334/// SSA update.
Evan Cheng11572ba2009-12-04 19:09:10 +0000335void TailDuplicatePass::AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
336 MachineBasicBlock *BB) {
337 DenseMap<unsigned, AvailableValsTy>::iterator LI= SSAUpdateVals.find(OrigReg);
Evan Cheng111e7622009-12-03 08:43:53 +0000338 if (LI != SSAUpdateVals.end())
Evan Cheng11572ba2009-12-04 19:09:10 +0000339 LI->second.push_back(std::make_pair(BB, NewReg));
Evan Cheng111e7622009-12-03 08:43:53 +0000340 else {
341 AvailableValsTy Vals;
Evan Cheng11572ba2009-12-04 19:09:10 +0000342 Vals.push_back(std::make_pair(BB, NewReg));
Evan Cheng111e7622009-12-03 08:43:53 +0000343 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
344 SSAUpdateVRs.push_back(OrigReg);
345 }
346}
347
Evan Cheng75eb5352009-12-07 10:15:19 +0000348/// ProcessPHI - Process PHI node in TailBB by turning it into a copy in PredBB.
349/// Remember the source register that's contributed by PredBB and update SSA
350/// update map.
Evan Cheng79fc6f42009-12-04 09:42:45 +0000351void TailDuplicatePass::ProcessPHI(MachineInstr *MI,
352 MachineBasicBlock *TailBB,
353 MachineBasicBlock *PredBB,
Evan Cheng75eb5352009-12-07 10:15:19 +0000354 DenseMap<unsigned, unsigned> &LocalVRMap,
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000355 SmallVector<std::pair<unsigned,unsigned>, 4> &Copies,
Rafael Espindola33b46582011-06-10 21:01:53 +0000356 const DenseSet<unsigned> &RegsUsedByPhi,
Rafael Espindola689d7d52011-06-09 23:22:56 +0000357 bool Remove) {
Evan Cheng79fc6f42009-12-04 09:42:45 +0000358 unsigned DefReg = MI->getOperand(0).getReg();
359 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
360 assert(SrcOpIdx && "Unable to find matching PHI source?");
361 unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
Evan Cheng75eb5352009-12-07 10:15:19 +0000362 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000363 LocalVRMap.insert(std::make_pair(DefReg, SrcReg));
Evan Cheng75eb5352009-12-07 10:15:19 +0000364
365 // Insert a copy from source to the end of the block. The def register is the
366 // available value liveout of the block.
367 unsigned NewDef = MRI->createVirtualRegister(RC);
368 Copies.push_back(std::make_pair(NewDef, SrcReg));
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000369 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
Evan Cheng75eb5352009-12-07 10:15:19 +0000370 AddSSAUpdateEntry(DefReg, NewDef, PredBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000371
Rafael Espindola689d7d52011-06-09 23:22:56 +0000372 if (!Remove)
373 return;
374
Evan Cheng79fc6f42009-12-04 09:42:45 +0000375 // Remove PredBB from the PHI node.
376 MI->RemoveOperand(SrcOpIdx+1);
377 MI->RemoveOperand(SrcOpIdx);
378 if (MI->getNumOperands() == 1)
379 MI->eraseFromParent();
380}
381
382/// DuplicateInstruction - Duplicate a TailBB instruction to PredBB and update
383/// the source operands due to earlier PHI translation.
384void TailDuplicatePass::DuplicateInstruction(MachineInstr *MI,
385 MachineBasicBlock *TailBB,
386 MachineBasicBlock *PredBB,
387 MachineFunction &MF,
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000388 DenseMap<unsigned, unsigned> &LocalVRMap,
389 const DenseSet<unsigned> &UsedByPhi) {
Jakob Stoklund Olesen30ac0462010-01-06 23:47:07 +0000390 MachineInstr *NewMI = TII->duplicate(MI, MF);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000391 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
392 MachineOperand &MO = NewMI->getOperand(i);
393 if (!MO.isReg())
394 continue;
395 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000396 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng79fc6f42009-12-04 09:42:45 +0000397 continue;
398 if (MO.isDef()) {
399 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
400 unsigned NewReg = MRI->createVirtualRegister(RC);
401 MO.setReg(NewReg);
402 LocalVRMap.insert(std::make_pair(Reg, NewReg));
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000403 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
Evan Cheng11572ba2009-12-04 19:09:10 +0000404 AddSSAUpdateEntry(Reg, NewReg, PredBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000405 } else {
406 DenseMap<unsigned, unsigned>::iterator VI = LocalVRMap.find(Reg);
407 if (VI != LocalVRMap.end())
408 MO.setReg(VI->second);
409 }
410 }
411 PredBB->insert(PredBB->end(), NewMI);
412}
413
414/// UpdateSuccessorsPHIs - After FromBB is tail duplicated into its predecessor
415/// blocks, the successors have gained new predecessors. Update the PHI
416/// instructions in them accordingly.
Evan Cheng75eb5352009-12-07 10:15:19 +0000417void
418TailDuplicatePass::UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
419 SmallVector<MachineBasicBlock*, 8> &TDBBs,
Evan Cheng79fc6f42009-12-04 09:42:45 +0000420 SmallSetVector<MachineBasicBlock*,8> &Succs) {
421 for (SmallSetVector<MachineBasicBlock*, 8>::iterator SI = Succs.begin(),
422 SE = Succs.end(); SI != SE; ++SI) {
423 MachineBasicBlock *SuccBB = *SI;
424 for (MachineBasicBlock::iterator II = SuccBB->begin(), EE = SuccBB->end();
425 II != EE; ++II) {
Chris Lattner518bb532010-02-09 19:54:29 +0000426 if (!II->isPHI())
Evan Cheng79fc6f42009-12-04 09:42:45 +0000427 break;
Evan Cheng75eb5352009-12-07 10:15:19 +0000428 unsigned Idx = 0;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000429 for (unsigned i = 1, e = II->getNumOperands(); i != e; i += 2) {
Evan Cheng75eb5352009-12-07 10:15:19 +0000430 MachineOperand &MO = II->getOperand(i+1);
431 if (MO.getMBB() == FromBB) {
432 Idx = i;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000433 break;
Evan Cheng75eb5352009-12-07 10:15:19 +0000434 }
435 }
436
437 assert(Idx != 0);
438 MachineOperand &MO0 = II->getOperand(Idx);
439 unsigned Reg = MO0.getReg();
440 if (isDead) {
441 // Folded into the previous BB.
442 // There could be duplicate phi source entries. FIXME: Should sdisel
443 // or earlier pass fixed this?
444 for (unsigned i = II->getNumOperands()-2; i != Idx; i -= 2) {
445 MachineOperand &MO = II->getOperand(i+1);
446 if (MO.getMBB() == FromBB) {
447 II->RemoveOperand(i+1);
448 II->RemoveOperand(i);
449 }
450 }
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000451 } else
452 Idx = 0;
453
454 // If Idx is set, the operands at Idx and Idx+1 must be removed.
455 // We reuse the location to avoid expensive RemoveOperand calls.
456
Evan Cheng75eb5352009-12-07 10:15:19 +0000457 DenseMap<unsigned,AvailableValsTy>::iterator LI=SSAUpdateVals.find(Reg);
458 if (LI != SSAUpdateVals.end()) {
459 // This register is defined in the tail block.
Evan Cheng79fc6f42009-12-04 09:42:45 +0000460 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
Evan Cheng11572ba2009-12-04 19:09:10 +0000461 MachineBasicBlock *SrcBB = LI->second[j].first;
Rafael Espindolad3f4eea2011-06-09 23:55:56 +0000462 // If we didn't duplicate a bb into a particular predecessor, we
463 // might still have added an entry to SSAUpdateVals to correcly
464 // recompute SSA. If that case, avoid adding a dummy extra argument
465 // this PHI.
466 if (!SrcBB->isSuccessor(SuccBB))
467 continue;
468
Evan Cheng11572ba2009-12-04 19:09:10 +0000469 unsigned SrcReg = LI->second[j].second;
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000470 if (Idx != 0) {
471 II->getOperand(Idx).setReg(SrcReg);
472 II->getOperand(Idx+1).setMBB(SrcBB);
473 Idx = 0;
474 } else {
475 II->addOperand(MachineOperand::CreateReg(SrcReg, false));
476 II->addOperand(MachineOperand::CreateMBB(SrcBB));
477 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000478 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000479 } else {
480 // Live in tail block, must also be live in predecessors.
481 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
482 MachineBasicBlock *SrcBB = TDBBs[j];
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000483 if (Idx != 0) {
484 II->getOperand(Idx).setReg(Reg);
485 II->getOperand(Idx+1).setMBB(SrcBB);
486 Idx = 0;
487 } else {
488 II->addOperand(MachineOperand::CreateReg(Reg, false));
489 II->addOperand(MachineOperand::CreateMBB(SrcBB));
490 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000491 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000492 }
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000493 if (Idx != 0) {
494 II->RemoveOperand(Idx+1);
495 II->RemoveOperand(Idx);
496 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000497 }
498 }
499}
500
Rafael Espindola54c25622011-06-09 19:54:42 +0000501/// shouldTailDuplicate - Determine if it is profitable to duplicate this block.
Evan Cheng75eb5352009-12-07 10:15:19 +0000502bool
Rafael Espindola54c25622011-06-09 19:54:42 +0000503TailDuplicatePass::shouldTailDuplicate(const MachineFunction &MF,
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000504 bool IsSimple,
Rafael Espindola54c25622011-06-09 19:54:42 +0000505 MachineBasicBlock &TailBB) {
506 // Only duplicate blocks that end with unconditional branches.
507 if (TailBB.canFallThrough())
508 return false;
509
Rafael Espindolaec324e52011-06-17 05:54:50 +0000510 // Don't try to tail-duplicate single-block loops.
511 if (TailBB.isSuccessor(&TailBB))
512 return false;
513
Rafael Espindola54c25622011-06-09 19:54:42 +0000514 // Set the limit on the cost to duplicate. When optimizing for size,
Bob Wilson15acadd2009-11-26 00:32:21 +0000515 // duplicate only one, because one branch instruction can be eliminated to
516 // compensate for the duplication.
517 unsigned MaxDuplicateCount;
Jakob Stoklund Olesen83520622011-01-30 20:38:12 +0000518 if (TailDuplicateSize.getNumOccurrences() == 0 &&
519 MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize))
Bob Wilson38582252009-11-30 18:56:45 +0000520 MaxDuplicateCount = 1;
Bob Wilson15acadd2009-11-26 00:32:21 +0000521 else
522 MaxDuplicateCount = TailDuplicateSize;
523
Rafael Espindolaec324e52011-06-17 05:54:50 +0000524 // If the target has hardware branch prediction that can handle indirect
525 // branches, duplicating them can often make them predictable when there
526 // are common paths through the code. The limit needs to be high enough
527 // to allow undoing the effects of tail merging and other optimizations
528 // that rearrange the predecessors of the indirect branch.
Bob Wilsoncb44b282010-01-16 00:42:25 +0000529
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000530 bool hasIndirectBR = false;
Rafael Espindolaec324e52011-06-17 05:54:50 +0000531 if (PreRegAlloc && !TailBB.empty()) {
532 const TargetInstrDesc &TID = TailBB.back().getDesc();
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000533 if (TID.isIndirectBranch()) {
Rafael Espindolaec324e52011-06-17 05:54:50 +0000534 MaxDuplicateCount = 20;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000535 hasIndirectBR = true;
536 }
Rafael Espindolaec324e52011-06-17 05:54:50 +0000537 }
Bob Wilsonbfdcf3b2010-01-15 06:29:17 +0000538
Bob Wilson15acadd2009-11-26 00:32:21 +0000539 // Check the instructions in the block to determine whether tail-duplication
540 // is invalid or unlikely to be profitable.
Bob Wilsonf1e01dc2009-12-02 17:15:24 +0000541 unsigned InstrCount = 0;
Rafael Espindola54c25622011-06-09 19:54:42 +0000542 for (MachineBasicBlock::const_iterator I = TailBB.begin(); I != TailBB.end();
543 ++I) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000544 // Non-duplicable things shouldn't be tail-duplicated.
Rafael Espindolaec324e52011-06-17 05:54:50 +0000545 if (I->getDesc().isNotDuplicable())
546 return false;
547
Evan Cheng79fc6f42009-12-04 09:42:45 +0000548 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
549 // A return may expand into a lot more instructions (e.g. reload of callee
550 // saved registers) after PEI.
Rafael Espindolaec324e52011-06-17 05:54:50 +0000551 if (PreRegAlloc && I->getDesc().isReturn())
552 return false;
553
554 // Avoid duplicating calls before register allocation. Calls presents a
555 // barrier to register allocation so duplicating them may end up increasing
556 // spills.
557 if (PreRegAlloc && I->getDesc().isCall())
558 return false;
559
Devang Patelcbe1e312010-03-16 21:02:07 +0000560 if (!I->isPHI() && !I->isDebugValue())
Bob Wilsonf1e01dc2009-12-02 17:15:24 +0000561 InstrCount += 1;
Rafael Espindolaec324e52011-06-17 05:54:50 +0000562
563 if (InstrCount > MaxDuplicateCount)
564 return false;
Bob Wilson15acadd2009-11-26 00:32:21 +0000565 }
Bob Wilson15acadd2009-11-26 00:32:21 +0000566
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000567 if (hasIndirectBR)
568 return true;
569
570 if (IsSimple)
571 return canCompletelyDuplicateBB(TailBB, IsSimple);
572
573 if (!PreRegAlloc)
574 return true;
575
576 return canCompletelyDuplicateBB(TailBB, IsSimple);
Rafael Espindola54c25622011-06-09 19:54:42 +0000577}
578
Rafael Espindola275c1f92011-06-20 04:16:35 +0000579/// isSimpleBB - True if this BB has only one unconditional jump.
580bool
581TailDuplicatePass::isSimpleBB(MachineBasicBlock *TailBB) {
582 if (TailBB->succ_size() != 1)
583 return false;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000584 if (TailBB->pred_empty())
585 return false;
Rafael Espindolad6379a92011-06-22 22:31:57 +0000586 MachineBasicBlock::iterator I = TailBB->begin();
Rafael Espindola275c1f92011-06-20 04:16:35 +0000587 MachineBasicBlock::iterator E = TailBB->end();
Rafael Espindolad6379a92011-06-22 22:31:57 +0000588 while (I != E && I->isDebugValue())
Rafael Espindola275c1f92011-06-20 04:16:35 +0000589 ++I;
590 if (I == E)
591 return true;
592 return I->getDesc().isUnconditionalBranch();
593}
594
595static bool
596bothUsedInPHI(const MachineBasicBlock &A,
597 SmallPtrSet<MachineBasicBlock*, 8> SuccsB) {
598 for (MachineBasicBlock::const_succ_iterator SI = A.succ_begin(),
599 SE = A.succ_end(); SI != SE; ++SI) {
600 MachineBasicBlock *BB = *SI;
601 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
602 return true;
603 }
604
605 return false;
606}
607
608bool
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000609TailDuplicatePass::canCompletelyDuplicateBB(MachineBasicBlock &BB,
610 bool isSimple) {
Rafael Espindola275c1f92011-06-20 04:16:35 +0000611 SmallPtrSet<MachineBasicBlock*, 8> Succs(BB.succ_begin(), BB.succ_end());
612
613 for (MachineBasicBlock::pred_iterator PI = BB.pred_begin(),
614 PE = BB.pred_end(); PI != PE; ++PI) {
615 MachineBasicBlock *PredBB = *PI;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000616
617 if (isSimple) {
618 if (PredBB->getLandingPadSuccessor())
619 return false;
620 if (bothUsedInPHI(*PredBB, Succs))
621 return false;
622 } else {
623 if (PredBB->succ_size() > 1)
624 return false;
625 }
626
Rafael Espindola275c1f92011-06-20 04:16:35 +0000627 MachineBasicBlock *PredTBB = NULL, *PredFBB = NULL;
628 SmallVector<MachineOperand, 4> PredCond;
629 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
630 return false;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000631
632 if (!isSimple && !PredCond.empty())
633 return false;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000634 }
635 return true;
636}
637
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000638void
Rafael Espindola275c1f92011-06-20 04:16:35 +0000639TailDuplicatePass::duplicateSimpleBB(MachineBasicBlock *TailBB,
640 SmallVector<MachineBasicBlock*, 8> &TDBBs,
641 const DenseSet<unsigned> &UsedByPhi,
642 SmallVector<MachineInstr*, 16> &Copies) {
Rafael Espindola275c1f92011-06-20 04:16:35 +0000643 SmallVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
644 TailBB->pred_end());
645 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
646 PE = Preds.end(); PI != PE; ++PI) {
647 MachineBasicBlock *PredBB = *PI;
648
649 MachineBasicBlock *PredTBB = NULL, *PredFBB = NULL;
650 SmallVector<MachineOperand, 4> PredCond;
651 bool NotAnalyzable =
652 TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true);
653 (void)NotAnalyzable;
654 assert(!NotAnalyzable && "Cannot duplicate this!");
655
656 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
657 << "From simple Succ: " << *TailBB);
658
659 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
Francois Pichet289a2792011-06-20 05:19:37 +0000660 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(PredBB));
Rafael Espindola275c1f92011-06-20 04:16:35 +0000661
662 DenseMap<unsigned, unsigned> LocalVRMap;
663 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
664 for (MachineBasicBlock::iterator I = TailBB->begin();
665 I != TailBB->end() && I->isPHI();) {
666 MachineInstr *MI = &*I;
667 ++I;
668 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
669 }
670 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
671 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
672 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
673 TII->get(TargetOpcode::COPY),
674 CopyInfos[i].first).addReg(CopyInfos[i].second));
675 }
676
677 // Make PredFBB explicit.
678 if (PredCond.empty())
679 PredFBB = PredTBB;
680
681 // Make fall through explicit.
682 if (!PredTBB)
683 PredTBB = NextBB;
684 if (!PredFBB)
685 PredFBB = NextBB;
686
687 // Redirect
688 if (PredFBB == TailBB)
689 PredFBB = NewTarget;
690 if (PredTBB == TailBB)
691 PredTBB = NewTarget;
692
693 // Make the branch unconditional if possible
Rafael Espindola689c2472011-06-20 14:11:42 +0000694 if (PredTBB == PredFBB) {
695 PredCond.clear();
Rafael Espindola275c1f92011-06-20 04:16:35 +0000696 PredFBB = NULL;
Rafael Espindola689c2472011-06-20 14:11:42 +0000697 }
Rafael Espindola275c1f92011-06-20 04:16:35 +0000698
699 // Avoid adding fall through branches.
700 if (PredFBB == NextBB)
701 PredFBB = NULL;
702 if (PredTBB == NextBB && PredFBB == NULL)
703 PredTBB = NULL;
704
705 TII->RemoveBranch(*PredBB);
706
707 if (PredTBB)
708 TII->InsertBranch(*PredBB, PredTBB, PredFBB, PredCond, DebugLoc());
709
710 PredBB->removeSuccessor(TailBB);
Rafael Espindola689c2472011-06-20 14:11:42 +0000711 unsigned NumSuccessors = PredBB->succ_size();
712 assert(NumSuccessors <= 1);
713 if (NumSuccessors == 0 || *PredBB->succ_begin() != NewTarget)
714 PredBB->addSuccessor(NewTarget);
Rafael Espindola275c1f92011-06-20 04:16:35 +0000715
716 TDBBs.push_back(PredBB);
Rafael Espindola275c1f92011-06-20 04:16:35 +0000717 }
Rafael Espindola275c1f92011-06-20 04:16:35 +0000718}
719
Rafael Espindola54c25622011-06-09 19:54:42 +0000720/// TailDuplicate - If it is profitable, duplicate TailBB's contents in each
721/// of its predecessors.
722bool
723TailDuplicatePass::TailDuplicate(MachineBasicBlock *TailBB, MachineFunction &MF,
724 SmallVector<MachineBasicBlock*, 8> &TDBBs,
725 SmallVector<MachineInstr*, 16> &Copies) {
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000726 bool IsSimple = isSimpleBB(TailBB);
727
728 if (!shouldTailDuplicate(MF, IsSimple, *TailBB))
Rafael Espindola54c25622011-06-09 19:54:42 +0000729 return false;
730
David Greene00dec1b2010-01-05 01:25:15 +0000731 DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
Evan Cheng75eb5352009-12-07 10:15:19 +0000732
Rafael Espindola275c1f92011-06-20 04:16:35 +0000733 DenseSet<unsigned> UsedByPhi;
734 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
735
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000736 if (IsSimple) {
737 duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
738 return true;
739 }
740
Rafael Espindola275c1f92011-06-20 04:16:35 +0000741
Bob Wilson15acadd2009-11-26 00:32:21 +0000742 // Iterate through all the unique predecessors and tail-duplicate this
743 // block into them, if possible. Copying the list ahead of time also
744 // avoids trouble with the predecessor list reallocating.
745 bool Changed = false;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000746 SmallSetVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
747 TailBB->pred_end());
Bob Wilson15acadd2009-11-26 00:32:21 +0000748 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
749 PE = Preds.end(); PI != PE; ++PI) {
750 MachineBasicBlock *PredBB = *PI;
751
752 assert(TailBB != PredBB &&
753 "Single-block loop should have been rejected earlier!");
Rafael Espindola9a9a3a52011-06-10 20:08:23 +0000754 // EH edges are ignored by AnalyzeBranch.
755 if (PredBB->succ_size() > 1)
756 continue;
Bob Wilson15acadd2009-11-26 00:32:21 +0000757
758 MachineBasicBlock *PredTBB, *PredFBB;
759 SmallVector<MachineOperand, 4> PredCond;
760 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
761 continue;
762 if (!PredCond.empty())
763 continue;
Bob Wilson15acadd2009-11-26 00:32:21 +0000764 // Don't duplicate into a fall-through predecessor (at least for now).
765 if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
766 continue;
767
David Greene00dec1b2010-01-05 01:25:15 +0000768 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
Bob Wilson15acadd2009-11-26 00:32:21 +0000769 << "From Succ: " << *TailBB);
770
Evan Cheng75eb5352009-12-07 10:15:19 +0000771 TDBBs.push_back(PredBB);
772
Bob Wilson15acadd2009-11-26 00:32:21 +0000773 // Remove PredBB's unconditional branch.
774 TII->RemoveBranch(*PredBB);
Evan Cheng111e7622009-12-03 08:43:53 +0000775
Bob Wilson15acadd2009-11-26 00:32:21 +0000776 // Clone the contents of TailBB into PredBB.
Evan Cheng111e7622009-12-03 08:43:53 +0000777 DenseMap<unsigned, unsigned> LocalVRMap;
Evan Cheng3466f132009-12-15 01:44:10 +0000778 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
Evan Cheng111e7622009-12-03 08:43:53 +0000779 MachineBasicBlock::iterator I = TailBB->begin();
Evan Cheng79fc6f42009-12-04 09:42:45 +0000780 while (I != TailBB->end()) {
781 MachineInstr *MI = &*I;
782 ++I;
Chris Lattner518bb532010-02-09 19:54:29 +0000783 if (MI->isPHI()) {
Evan Cheng111e7622009-12-03 08:43:53 +0000784 // Replace the uses of the def of the PHI with the register coming
785 // from PredBB.
Rafael Espindola689d7d52011-06-09 23:22:56 +0000786 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000787 } else {
788 // Replace def of virtual registers with new registers, and update
789 // uses with PHI source register or the new registers.
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000790 DuplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap, UsedByPhi);
Evan Cheng111e7622009-12-03 08:43:53 +0000791 }
Bob Wilson15acadd2009-11-26 00:32:21 +0000792 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000793 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
Evan Cheng3466f132009-12-15 01:44:10 +0000794 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +0000795 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
796 TII->get(TargetOpcode::COPY),
797 CopyInfos[i].first).addReg(CopyInfos[i].second));
Evan Cheng75eb5352009-12-07 10:15:19 +0000798 }
Rafael Espindolaec324e52011-06-17 05:54:50 +0000799
800 // Simplify
801 TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true);
802
Bob Wilson15acadd2009-11-26 00:32:21 +0000803 NumInstrDups += TailBB->size() - 1; // subtract one for removed branch
804
805 // Update the CFG.
806 PredBB->removeSuccessor(PredBB->succ_begin());
807 assert(PredBB->succ_empty() &&
808 "TailDuplicate called on block with multiple successors!");
809 for (MachineBasicBlock::succ_iterator I = TailBB->succ_begin(),
Evan Cheng79fc6f42009-12-04 09:42:45 +0000810 E = TailBB->succ_end(); I != E; ++I)
811 PredBB->addSuccessor(*I);
Bob Wilson15acadd2009-11-26 00:32:21 +0000812
813 Changed = true;
814 ++NumTailDups;
815 }
816
817 // If TailBB was duplicated into all its predecessors except for the prior
818 // block, which falls through unconditionally, move the contents of this
819 // block into the prior block.
Evan Cheng79fc6f42009-12-04 09:42:45 +0000820 MachineBasicBlock *PrevBB = prior(MachineFunction::iterator(TailBB));
Bob Wilson15acadd2009-11-26 00:32:21 +0000821 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
822 SmallVector<MachineOperand, 4> PriorCond;
Bob Wilson15acadd2009-11-26 00:32:21 +0000823 // This has to check PrevBB->succ_size() because EH edges are ignored by
824 // AnalyzeBranch.
Rafael Espindolaa899b222011-06-09 21:43:25 +0000825 if (PrevBB->succ_size() == 1 &&
826 !TII->AnalyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) &&
827 PriorCond.empty() && !PriorTBB && TailBB->pred_size() == 1 &&
Bob Wilson15acadd2009-11-26 00:32:21 +0000828 !TailBB->hasAddressTaken()) {
David Greene00dec1b2010-01-05 01:25:15 +0000829 DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
Bob Wilson15acadd2009-11-26 00:32:21 +0000830 << "From MBB: " << *TailBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000831 if (PreRegAlloc) {
832 DenseMap<unsigned, unsigned> LocalVRMap;
Evan Cheng3466f132009-12-15 01:44:10 +0000833 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000834 MachineBasicBlock::iterator I = TailBB->begin();
835 // Process PHI instructions first.
Chris Lattner518bb532010-02-09 19:54:29 +0000836 while (I != TailBB->end() && I->isPHI()) {
Evan Cheng79fc6f42009-12-04 09:42:45 +0000837 // Replace the uses of the def of the PHI with the register coming
838 // from PredBB.
839 MachineInstr *MI = &*I++;
Rafael Espindola689d7d52011-06-09 23:22:56 +0000840 ProcessPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000841 if (MI->getParent())
842 MI->eraseFromParent();
843 }
844
845 // Now copy the non-PHI instructions.
846 while (I != TailBB->end()) {
847 // Replace def of virtual registers with new registers, and update
848 // uses with PHI source register or the new registers.
849 MachineInstr *MI = &*I++;
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000850 DuplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap, UsedByPhi);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000851 MI->eraseFromParent();
852 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000853 MachineBasicBlock::iterator Loc = PrevBB->getFirstTerminator();
Evan Cheng3466f132009-12-15 01:44:10 +0000854 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +0000855 Copies.push_back(BuildMI(*PrevBB, Loc, DebugLoc(),
856 TII->get(TargetOpcode::COPY),
857 CopyInfos[i].first)
858 .addReg(CopyInfos[i].second));
Evan Cheng75eb5352009-12-07 10:15:19 +0000859 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000860 } else {
861 // No PHIs to worry about, just splice the instructions over.
862 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
863 }
864 PrevBB->removeSuccessor(PrevBB->succ_begin());
865 assert(PrevBB->succ_empty());
866 PrevBB->transferSuccessors(TailBB);
Evan Cheng75eb5352009-12-07 10:15:19 +0000867 TDBBs.push_back(PrevBB);
Bob Wilson15acadd2009-11-26 00:32:21 +0000868 Changed = true;
869 }
870
Rafael Espindola689d7d52011-06-09 23:22:56 +0000871 // If this is after register allocation, there are no phis to fix.
872 if (!PreRegAlloc)
873 return Changed;
874
875 // If we made no changes so far, we are safe.
876 if (!Changed)
877 return Changed;
878
879
880 // Handle the nasty case in that we duplicated a block that is part of a loop
881 // into some but not all of its predecessors. For example:
Rafael Espindola4d7b4572011-06-09 23:51:45 +0000882 // 1 -> 2 <-> 3 |
883 // \ |
884 // \---> rest |
Rafael Espindola689d7d52011-06-09 23:22:56 +0000885 // if we duplicate 2 into 1 but not into 3, we end up with
Rafael Espindola4d7b4572011-06-09 23:51:45 +0000886 // 12 -> 3 <-> 2 -> rest |
887 // \ / |
888 // \----->-----/ |
Rafael Espindola689d7d52011-06-09 23:22:56 +0000889 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
890 // with a phi in 3 (which now dominates 2).
891 // What we do here is introduce a copy in 3 of the register defined by the
892 // phi, just like when we are duplicating 2 into 3, but we don't copy any
893 // real instructions or remove the 3 -> 2 edge from the phi in 2.
894 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
895 PE = Preds.end(); PI != PE; ++PI) {
896 MachineBasicBlock *PredBB = *PI;
897 if (std::find(TDBBs.begin(), TDBBs.end(), PredBB) != TDBBs.end())
898 continue;
899
900 // EH edges
901 if (PredBB->succ_size() != 1)
902 continue;
903
904 DenseMap<unsigned, unsigned> LocalVRMap;
905 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
906 MachineBasicBlock::iterator I = TailBB->begin();
907 // Process PHI instructions first.
908 while (I != TailBB->end() && I->isPHI()) {
909 // Replace the uses of the def of the PHI with the register coming
910 // from PredBB.
911 MachineInstr *MI = &*I++;
912 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
913 }
914 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
915 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
916 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
917 TII->get(TargetOpcode::COPY),
918 CopyInfos[i].first).addReg(CopyInfos[i].second));
919 }
920 }
921
Bob Wilson15acadd2009-11-26 00:32:21 +0000922 return Changed;
923}
924
925/// RemoveDeadBlock - Remove the specified dead machine basic block from the
926/// function, updating the CFG.
Bob Wilson2d521e52009-11-26 21:38:41 +0000927void TailDuplicatePass::RemoveDeadBlock(MachineBasicBlock *MBB) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000928 assert(MBB->pred_empty() && "MBB must be dead!");
David Greene00dec1b2010-01-05 01:25:15 +0000929 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
Bob Wilson15acadd2009-11-26 00:32:21 +0000930
931 // Remove all successors.
932 while (!MBB->succ_empty())
933 MBB->removeSuccessor(MBB->succ_end()-1);
934
Bob Wilson15acadd2009-11-26 00:32:21 +0000935 // Remove the block.
936 MBB->eraseFromParent();
937}