blob: 93acd5826f13f0774ad75c3300c5bfd42b016b72 [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,
84 SmallVector<std::pair<unsigned,unsigned>, 4> &Copies);
Evan Cheng79fc6f42009-12-04 09:42:45 +000085 void DuplicateInstruction(MachineInstr *MI,
86 MachineBasicBlock *TailBB,
87 MachineBasicBlock *PredBB,
88 MachineFunction &MF,
89 DenseMap<unsigned, unsigned> &LocalVRMap);
Evan Cheng75eb5352009-12-07 10:15:19 +000090 void UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
91 SmallVector<MachineBasicBlock*, 8> &TDBBs,
92 SmallSetVector<MachineBasicBlock*, 8> &Succs);
Bob Wilson15acadd2009-11-26 00:32:21 +000093 bool TailDuplicateBlocks(MachineFunction &MF);
Rafael Espindola54c25622011-06-09 19:54:42 +000094 bool shouldTailDuplicate(const MachineFunction &MF,
95 MachineBasicBlock &TailBB);
Evan Cheng75eb5352009-12-07 10:15:19 +000096 bool TailDuplicate(MachineBasicBlock *TailBB, MachineFunction &MF,
Evan Cheng3466f132009-12-15 01:44:10 +000097 SmallVector<MachineBasicBlock*, 8> &TDBBs,
98 SmallVector<MachineInstr*, 16> &Copies);
Bob Wilson15acadd2009-11-26 00:32:21 +000099 void RemoveDeadBlock(MachineBasicBlock *MBB);
100 };
101
Bob Wilson2d521e52009-11-26 21:38:41 +0000102 char TailDuplicatePass::ID = 0;
Bob Wilson15acadd2009-11-26 00:32:21 +0000103}
104
Evan Cheng79fc6f42009-12-04 09:42:45 +0000105FunctionPass *llvm::createTailDuplicatePass(bool PreRegAlloc) {
106 return new TailDuplicatePass(PreRegAlloc);
Bob Wilson15acadd2009-11-26 00:32:21 +0000107}
108
Bob Wilson2d521e52009-11-26 21:38:41 +0000109bool TailDuplicatePass::runOnMachineFunction(MachineFunction &MF) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000110 TII = MF.getTarget().getInstrInfo();
Evan Cheng111e7622009-12-03 08:43:53 +0000111 MRI = &MF.getRegInfo();
Bob Wilson15acadd2009-11-26 00:32:21 +0000112 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
113
114 bool MadeChange = false;
Jakob Stoklund Olesen057d5392010-01-15 19:59:57 +0000115 while (TailDuplicateBlocks(MF))
116 MadeChange = true;
Bob Wilson15acadd2009-11-26 00:32:21 +0000117
118 return MadeChange;
119}
120
Evan Cheng75eb5352009-12-07 10:15:19 +0000121static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
122 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
123 MachineBasicBlock *MBB = I;
124 SmallSetVector<MachineBasicBlock*, 8> Preds(MBB->pred_begin(),
125 MBB->pred_end());
126 MachineBasicBlock::iterator MI = MBB->begin();
127 while (MI != MBB->end()) {
Chris Lattner518bb532010-02-09 19:54:29 +0000128 if (!MI->isPHI())
Evan Cheng75eb5352009-12-07 10:15:19 +0000129 break;
130 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
131 PE = Preds.end(); PI != PE; ++PI) {
132 MachineBasicBlock *PredBB = *PI;
133 bool Found = false;
134 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
135 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
136 if (PHIBB == PredBB) {
137 Found = true;
138 break;
139 }
140 }
141 if (!Found) {
David Greene00dec1b2010-01-05 01:25:15 +0000142 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
143 dbgs() << " missing input from predecessor BB#"
Evan Cheng75eb5352009-12-07 10:15:19 +0000144 << PredBB->getNumber() << '\n';
145 llvm_unreachable(0);
146 }
147 }
148
149 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
150 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
151 if (CheckExtra && !Preds.count(PHIBB)) {
152 // This is not a hard error.
David Greene00dec1b2010-01-05 01:25:15 +0000153 dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber()
Evan Cheng75eb5352009-12-07 10:15:19 +0000154 << ": " << *MI;
David Greene00dec1b2010-01-05 01:25:15 +0000155 dbgs() << " extra input from predecessor BB#"
Evan Cheng75eb5352009-12-07 10:15:19 +0000156 << PHIBB->getNumber() << '\n';
157 }
158 if (PHIBB->getNumber() < 0) {
David Greene00dec1b2010-01-05 01:25:15 +0000159 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
160 dbgs() << " non-existing BB#" << PHIBB->getNumber() << '\n';
Evan Cheng75eb5352009-12-07 10:15:19 +0000161 llvm_unreachable(0);
162 }
163 }
164 ++MI;
165 }
166 }
167}
168
Bob Wilson15acadd2009-11-26 00:32:21 +0000169/// TailDuplicateBlocks - Look for small blocks that are unconditionally
170/// branched to and do not fall through. Tail-duplicate their instructions
171/// into their predecessors to eliminate (dynamic) branches.
Bob Wilson2d521e52009-11-26 21:38:41 +0000172bool TailDuplicatePass::TailDuplicateBlocks(MachineFunction &MF) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000173 bool MadeChange = false;
174
Evan Cheng75eb5352009-12-07 10:15:19 +0000175 if (PreRegAlloc && TailDupVerify) {
David Greene00dec1b2010-01-05 01:25:15 +0000176 DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
Evan Cheng75eb5352009-12-07 10:15:19 +0000177 VerifyPHIs(MF, true);
178 }
179
180 SmallVector<MachineInstr*, 8> NewPHIs;
181 MachineSSAUpdater SSAUpdate(MF, &NewPHIs);
182
Bob Wilson15acadd2009-11-26 00:32:21 +0000183 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
184 MachineBasicBlock *MBB = I++;
185
Evan Cheng75eb5352009-12-07 10:15:19 +0000186 if (NumTails == TailDupLimit)
187 break;
188
Evan Cheng75eb5352009-12-07 10:15:19 +0000189 // Save the successors list.
190 SmallSetVector<MachineBasicBlock*, 8> Succs(MBB->succ_begin(),
191 MBB->succ_end());
Bob Wilson15acadd2009-11-26 00:32:21 +0000192
Evan Cheng75eb5352009-12-07 10:15:19 +0000193 SmallVector<MachineBasicBlock*, 8> TDBBs;
Evan Cheng3466f132009-12-15 01:44:10 +0000194 SmallVector<MachineInstr*, 16> Copies;
195 if (TailDuplicate(MBB, MF, TDBBs, Copies)) {
Evan Cheng75eb5352009-12-07 10:15:19 +0000196 ++NumTails;
197
198 // TailBB's immediate successors are now successors of those predecessors
199 // which duplicated TailBB. Add the predecessors as sources to the PHI
200 // instructions.
201 bool isDead = MBB->pred_empty();
202 if (PreRegAlloc)
203 UpdateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
204
205 // If it is dead, remove it.
206 if (isDead) {
207 NumInstrDups -= MBB->size();
208 RemoveDeadBlock(MBB);
209 ++NumDeadBlocks;
210 }
211
212 // Update SSA form.
213 if (!SSAUpdateVRs.empty()) {
214 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
215 unsigned VReg = SSAUpdateVRs[i];
216 SSAUpdate.Initialize(VReg);
217
218 // If the original definition is still around, add it as an available
219 // value.
220 MachineInstr *DefMI = MRI->getVRegDef(VReg);
221 MachineBasicBlock *DefBB = 0;
222 if (DefMI) {
223 DefBB = DefMI->getParent();
224 SSAUpdate.AddAvailableValue(DefBB, VReg);
225 }
226
227 // Add the new vregs as available values.
228 DenseMap<unsigned, AvailableValsTy>::iterator LI =
229 SSAUpdateVals.find(VReg);
230 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
231 MachineBasicBlock *SrcBB = LI->second[j].first;
232 unsigned SrcReg = LI->second[j].second;
233 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
234 }
235
236 // Rewrite uses that are outside of the original def's block.
237 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
238 while (UI != MRI->use_end()) {
239 MachineOperand &UseMO = UI.getOperand();
240 MachineInstr *UseMI = &*UI;
241 ++UI;
Rafael Espindolac2e9a502011-06-09 20:55:41 +0000242 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
Evan Cheng75eb5352009-12-07 10:15:19 +0000243 continue;
244 SSAUpdate.RewriteUse(UseMO);
Evan Cheng75eb5352009-12-07 10:15:19 +0000245 }
246 }
247
248 SSAUpdateVRs.clear();
249 SSAUpdateVals.clear();
250 }
251
Bob Wilsonbfdcf3b2010-01-15 06:29:17 +0000252 // Eliminate some of the copies inserted by tail duplication to maintain
Evan Cheng3466f132009-12-15 01:44:10 +0000253 // SSA form.
254 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
255 MachineInstr *Copy = Copies[i];
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000256 if (!Copy->isCopy())
257 continue;
258 unsigned Dst = Copy->getOperand(0).getReg();
259 unsigned Src = Copy->getOperand(1).getReg();
260 MachineRegisterInfo::use_iterator UI = MRI->use_begin(Src);
261 if (++UI == MRI->use_end()) {
262 // Copy is the only use. Do trivial copy propagation here.
263 MRI->replaceRegWith(Dst, Src);
264 Copy->eraseFromParent();
Evan Cheng3466f132009-12-15 01:44:10 +0000265 }
266 }
267
Evan Cheng75eb5352009-12-07 10:15:19 +0000268 if (PreRegAlloc && TailDupVerify)
269 VerifyPHIs(MF, false);
Bob Wilson15acadd2009-11-26 00:32:21 +0000270 MadeChange = true;
Bob Wilson15acadd2009-11-26 00:32:21 +0000271 }
272 }
Rafael Espindolad69f85e2011-06-08 14:23:19 +0000273 NumAddedPHIs += NewPHIs.size();
Evan Cheng111e7622009-12-03 08:43:53 +0000274
Bob Wilson15acadd2009-11-26 00:32:21 +0000275 return MadeChange;
276}
277
Evan Cheng111e7622009-12-03 08:43:53 +0000278static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
279 const MachineRegisterInfo *MRI) {
280 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
281 UE = MRI->use_end(); UI != UE; ++UI) {
282 MachineInstr *UseMI = &*UI;
283 if (UseMI->getParent() != BB)
284 return true;
285 }
286 return false;
287}
288
289static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
290 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
291 if (MI->getOperand(i+1).getMBB() == SrcBB)
292 return i;
293 return 0;
294}
295
296/// AddSSAUpdateEntry - Add a definition and source virtual registers pair for
297/// SSA update.
Evan Cheng11572ba2009-12-04 19:09:10 +0000298void TailDuplicatePass::AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
299 MachineBasicBlock *BB) {
300 DenseMap<unsigned, AvailableValsTy>::iterator LI= SSAUpdateVals.find(OrigReg);
Evan Cheng111e7622009-12-03 08:43:53 +0000301 if (LI != SSAUpdateVals.end())
Evan Cheng11572ba2009-12-04 19:09:10 +0000302 LI->second.push_back(std::make_pair(BB, NewReg));
Evan Cheng111e7622009-12-03 08:43:53 +0000303 else {
304 AvailableValsTy Vals;
Evan Cheng11572ba2009-12-04 19:09:10 +0000305 Vals.push_back(std::make_pair(BB, NewReg));
Evan Cheng111e7622009-12-03 08:43:53 +0000306 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
307 SSAUpdateVRs.push_back(OrigReg);
308 }
309}
310
Evan Cheng75eb5352009-12-07 10:15:19 +0000311/// ProcessPHI - Process PHI node in TailBB by turning it into a copy in PredBB.
312/// Remember the source register that's contributed by PredBB and update SSA
313/// update map.
Evan Cheng79fc6f42009-12-04 09:42:45 +0000314void TailDuplicatePass::ProcessPHI(MachineInstr *MI,
315 MachineBasicBlock *TailBB,
316 MachineBasicBlock *PredBB,
Evan Cheng75eb5352009-12-07 10:15:19 +0000317 DenseMap<unsigned, unsigned> &LocalVRMap,
318 SmallVector<std::pair<unsigned,unsigned>, 4> &Copies) {
Evan Cheng79fc6f42009-12-04 09:42:45 +0000319 unsigned DefReg = MI->getOperand(0).getReg();
320 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
321 assert(SrcOpIdx && "Unable to find matching PHI source?");
322 unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
Evan Cheng75eb5352009-12-07 10:15:19 +0000323 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000324 LocalVRMap.insert(std::make_pair(DefReg, SrcReg));
Evan Cheng75eb5352009-12-07 10:15:19 +0000325
326 // Insert a copy from source to the end of the block. The def register is the
327 // available value liveout of the block.
328 unsigned NewDef = MRI->createVirtualRegister(RC);
329 Copies.push_back(std::make_pair(NewDef, SrcReg));
Evan Cheng79fc6f42009-12-04 09:42:45 +0000330 if (isDefLiveOut(DefReg, TailBB, MRI))
Evan Cheng75eb5352009-12-07 10:15:19 +0000331 AddSSAUpdateEntry(DefReg, NewDef, PredBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000332
333 // Remove PredBB from the PHI node.
334 MI->RemoveOperand(SrcOpIdx+1);
335 MI->RemoveOperand(SrcOpIdx);
336 if (MI->getNumOperands() == 1)
337 MI->eraseFromParent();
338}
339
340/// DuplicateInstruction - Duplicate a TailBB instruction to PredBB and update
341/// the source operands due to earlier PHI translation.
342void TailDuplicatePass::DuplicateInstruction(MachineInstr *MI,
343 MachineBasicBlock *TailBB,
344 MachineBasicBlock *PredBB,
345 MachineFunction &MF,
346 DenseMap<unsigned, unsigned> &LocalVRMap) {
Jakob Stoklund Olesen30ac0462010-01-06 23:47:07 +0000347 MachineInstr *NewMI = TII->duplicate(MI, MF);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000348 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
349 MachineOperand &MO = NewMI->getOperand(i);
350 if (!MO.isReg())
351 continue;
352 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000353 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng79fc6f42009-12-04 09:42:45 +0000354 continue;
355 if (MO.isDef()) {
356 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
357 unsigned NewReg = MRI->createVirtualRegister(RC);
358 MO.setReg(NewReg);
359 LocalVRMap.insert(std::make_pair(Reg, NewReg));
360 if (isDefLiveOut(Reg, TailBB, MRI))
Evan Cheng11572ba2009-12-04 19:09:10 +0000361 AddSSAUpdateEntry(Reg, NewReg, PredBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000362 } else {
363 DenseMap<unsigned, unsigned>::iterator VI = LocalVRMap.find(Reg);
364 if (VI != LocalVRMap.end())
365 MO.setReg(VI->second);
366 }
367 }
368 PredBB->insert(PredBB->end(), NewMI);
369}
370
371/// UpdateSuccessorsPHIs - After FromBB is tail duplicated into its predecessor
372/// blocks, the successors have gained new predecessors. Update the PHI
373/// instructions in them accordingly.
Evan Cheng75eb5352009-12-07 10:15:19 +0000374void
375TailDuplicatePass::UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
376 SmallVector<MachineBasicBlock*, 8> &TDBBs,
Evan Cheng79fc6f42009-12-04 09:42:45 +0000377 SmallSetVector<MachineBasicBlock*,8> &Succs) {
378 for (SmallSetVector<MachineBasicBlock*, 8>::iterator SI = Succs.begin(),
379 SE = Succs.end(); SI != SE; ++SI) {
380 MachineBasicBlock *SuccBB = *SI;
381 for (MachineBasicBlock::iterator II = SuccBB->begin(), EE = SuccBB->end();
382 II != EE; ++II) {
Chris Lattner518bb532010-02-09 19:54:29 +0000383 if (!II->isPHI())
Evan Cheng79fc6f42009-12-04 09:42:45 +0000384 break;
Evan Cheng75eb5352009-12-07 10:15:19 +0000385 unsigned Idx = 0;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000386 for (unsigned i = 1, e = II->getNumOperands(); i != e; i += 2) {
Evan Cheng75eb5352009-12-07 10:15:19 +0000387 MachineOperand &MO = II->getOperand(i+1);
388 if (MO.getMBB() == FromBB) {
389 Idx = i;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000390 break;
Evan Cheng75eb5352009-12-07 10:15:19 +0000391 }
392 }
393
394 assert(Idx != 0);
395 MachineOperand &MO0 = II->getOperand(Idx);
396 unsigned Reg = MO0.getReg();
397 if (isDead) {
398 // Folded into the previous BB.
399 // There could be duplicate phi source entries. FIXME: Should sdisel
400 // or earlier pass fixed this?
401 for (unsigned i = II->getNumOperands()-2; i != Idx; i -= 2) {
402 MachineOperand &MO = II->getOperand(i+1);
403 if (MO.getMBB() == FromBB) {
404 II->RemoveOperand(i+1);
405 II->RemoveOperand(i);
406 }
407 }
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000408 } else
409 Idx = 0;
410
411 // If Idx is set, the operands at Idx and Idx+1 must be removed.
412 // We reuse the location to avoid expensive RemoveOperand calls.
413
Evan Cheng75eb5352009-12-07 10:15:19 +0000414 DenseMap<unsigned,AvailableValsTy>::iterator LI=SSAUpdateVals.find(Reg);
415 if (LI != SSAUpdateVals.end()) {
416 // This register is defined in the tail block.
Evan Cheng79fc6f42009-12-04 09:42:45 +0000417 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
Evan Cheng11572ba2009-12-04 19:09:10 +0000418 MachineBasicBlock *SrcBB = LI->second[j].first;
419 unsigned SrcReg = LI->second[j].second;
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000420 if (Idx != 0) {
421 II->getOperand(Idx).setReg(SrcReg);
422 II->getOperand(Idx+1).setMBB(SrcBB);
423 Idx = 0;
424 } else {
425 II->addOperand(MachineOperand::CreateReg(SrcReg, false));
426 II->addOperand(MachineOperand::CreateMBB(SrcBB));
427 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000428 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000429 } else {
430 // Live in tail block, must also be live in predecessors.
431 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
432 MachineBasicBlock *SrcBB = TDBBs[j];
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000433 if (Idx != 0) {
434 II->getOperand(Idx).setReg(Reg);
435 II->getOperand(Idx+1).setMBB(SrcBB);
436 Idx = 0;
437 } else {
438 II->addOperand(MachineOperand::CreateReg(Reg, false));
439 II->addOperand(MachineOperand::CreateMBB(SrcBB));
440 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000441 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000442 }
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000443 if (Idx != 0) {
444 II->RemoveOperand(Idx+1);
445 II->RemoveOperand(Idx);
446 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000447 }
448 }
449}
450
Rafael Espindola54c25622011-06-09 19:54:42 +0000451/// shouldTailDuplicate - Determine if it is profitable to duplicate this block.
Evan Cheng75eb5352009-12-07 10:15:19 +0000452bool
Rafael Espindola54c25622011-06-09 19:54:42 +0000453TailDuplicatePass::shouldTailDuplicate(const MachineFunction &MF,
454 MachineBasicBlock &TailBB) {
455 // Only duplicate blocks that end with unconditional branches.
456 if (TailBB.canFallThrough())
457 return false;
458
459 // Set the limit on the cost to duplicate. When optimizing for size,
Bob Wilson15acadd2009-11-26 00:32:21 +0000460 // duplicate only one, because one branch instruction can be eliminated to
461 // compensate for the duplication.
462 unsigned MaxDuplicateCount;
Jakob Stoklund Olesen83520622011-01-30 20:38:12 +0000463 if (TailDuplicateSize.getNumOccurrences() == 0 &&
464 MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize))
Bob Wilson38582252009-11-30 18:56:45 +0000465 MaxDuplicateCount = 1;
Bob Wilson15acadd2009-11-26 00:32:21 +0000466 else
467 MaxDuplicateCount = TailDuplicateSize;
468
Bob Wilsoncb44b282010-01-16 00:42:25 +0000469 if (PreRegAlloc) {
Rafael Espindola54c25622011-06-09 19:54:42 +0000470 if (TailBB.empty())
Evan Chengc3f507f2011-01-29 04:46:23 +0000471 return false;
Rafael Espindola54c25622011-06-09 19:54:42 +0000472 const TargetInstrDesc &TID = TailBB.back().getDesc();
Evan Chengc3f507f2011-01-29 04:46:23 +0000473 // Pre-regalloc tail duplication hurts compile time and doesn't help
Rafael Espindola54c25622011-06-09 19:54:42 +0000474 // much except for indirect branches.
475 if (!TID.isIndirectBranch())
Bob Wilsoncb44b282010-01-16 00:42:25 +0000476 return false;
477 // If the target has hardware branch prediction that can handle indirect
478 // branches, duplicating them can often make them predictable when there
479 // are common paths through the code. The limit needs to be high enough
480 // to allow undoing the effects of tail merging and other optimizations
481 // that rearrange the predecessors of the indirect branch.
482 MaxDuplicateCount = 20;
483 }
484
Bob Wilsonbfdcf3b2010-01-15 06:29:17 +0000485 // Don't try to tail-duplicate single-block loops.
Rafael Espindola54c25622011-06-09 19:54:42 +0000486 if (TailBB.isSuccessor(&TailBB))
Bob Wilsonbfdcf3b2010-01-15 06:29:17 +0000487 return false;
488
Bob Wilson15acadd2009-11-26 00:32:21 +0000489 // Check the instructions in the block to determine whether tail-duplication
490 // is invalid or unlikely to be profitable.
Bob Wilsonf1e01dc2009-12-02 17:15:24 +0000491 unsigned InstrCount = 0;
Bob Wilson15acadd2009-11-26 00:32:21 +0000492 bool HasCall = false;
Rafael Espindola54c25622011-06-09 19:54:42 +0000493 for (MachineBasicBlock::const_iterator I = TailBB.begin(); I != TailBB.end();
494 ++I) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000495 // Non-duplicable things shouldn't be tail-duplicated.
496 if (I->getDesc().isNotDuplicable()) return false;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000497 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
498 // A return may expand into a lot more instructions (e.g. reload of callee
499 // saved registers) after PEI.
500 if (PreRegAlloc && I->getDesc().isReturn()) return false;
Bob Wilson15acadd2009-11-26 00:32:21 +0000501 // Don't duplicate more than the threshold.
Bob Wilsonf1e01dc2009-12-02 17:15:24 +0000502 if (InstrCount == MaxDuplicateCount) return false;
Bob Wilson15acadd2009-11-26 00:32:21 +0000503 // Remember if we saw a call.
504 if (I->getDesc().isCall()) HasCall = true;
Devang Patelcbe1e312010-03-16 21:02:07 +0000505 if (!I->isPHI() && !I->isDebugValue())
Bob Wilsonf1e01dc2009-12-02 17:15:24 +0000506 InstrCount += 1;
Bob Wilson15acadd2009-11-26 00:32:21 +0000507 }
Evan Chengc8b90e22011-02-04 01:10:12 +0000508 // Don't tail-duplicate calls before register allocation. Calls presents a
509 // barrier to register allocation so duplicating them may end up increasing
510 // spills.
Evan Chengc3f507f2011-01-29 04:46:23 +0000511 if (InstrCount > 1 && (PreRegAlloc && HasCall))
Bob Wilson15acadd2009-11-26 00:32:21 +0000512 return false;
513
Rafael Espindola54c25622011-06-09 19:54:42 +0000514 return true;
515}
516
517/// TailDuplicate - If it is profitable, duplicate TailBB's contents in each
518/// of its predecessors.
519bool
520TailDuplicatePass::TailDuplicate(MachineBasicBlock *TailBB, MachineFunction &MF,
521 SmallVector<MachineBasicBlock*, 8> &TDBBs,
522 SmallVector<MachineInstr*, 16> &Copies) {
523 if (!shouldTailDuplicate(MF, *TailBB))
524 return false;
525
David Greene00dec1b2010-01-05 01:25:15 +0000526 DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
Evan Cheng75eb5352009-12-07 10:15:19 +0000527
Bob Wilson15acadd2009-11-26 00:32:21 +0000528 // Iterate through all the unique predecessors and tail-duplicate this
529 // block into them, if possible. Copying the list ahead of time also
530 // avoids trouble with the predecessor list reallocating.
531 bool Changed = false;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000532 SmallSetVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
533 TailBB->pred_end());
Bob Wilson15acadd2009-11-26 00:32:21 +0000534 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
535 PE = Preds.end(); PI != PE; ++PI) {
536 MachineBasicBlock *PredBB = *PI;
537
538 assert(TailBB != PredBB &&
539 "Single-block loop should have been rejected earlier!");
540 if (PredBB->succ_size() > 1) continue;
541
542 MachineBasicBlock *PredTBB, *PredFBB;
543 SmallVector<MachineOperand, 4> PredCond;
Rafael Espindolaa899b222011-06-09 21:43:25 +0000544 // EH edges are ignored by AnalyzeBranch.
545 if (PredBB->succ_size() != 1)
546 continue;
Bob Wilson15acadd2009-11-26 00:32:21 +0000547 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
548 continue;
549 if (!PredCond.empty())
550 continue;
Bob Wilson15acadd2009-11-26 00:32:21 +0000551 // Don't duplicate into a fall-through predecessor (at least for now).
552 if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
553 continue;
554
David Greene00dec1b2010-01-05 01:25:15 +0000555 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
Bob Wilson15acadd2009-11-26 00:32:21 +0000556 << "From Succ: " << *TailBB);
557
Evan Cheng75eb5352009-12-07 10:15:19 +0000558 TDBBs.push_back(PredBB);
559
Bob Wilson15acadd2009-11-26 00:32:21 +0000560 // Remove PredBB's unconditional branch.
561 TII->RemoveBranch(*PredBB);
Evan Cheng111e7622009-12-03 08:43:53 +0000562
Bob Wilson15acadd2009-11-26 00:32:21 +0000563 // Clone the contents of TailBB into PredBB.
Evan Cheng111e7622009-12-03 08:43:53 +0000564 DenseMap<unsigned, unsigned> LocalVRMap;
Evan Cheng3466f132009-12-15 01:44:10 +0000565 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
Evan Cheng111e7622009-12-03 08:43:53 +0000566 MachineBasicBlock::iterator I = TailBB->begin();
Evan Cheng79fc6f42009-12-04 09:42:45 +0000567 while (I != TailBB->end()) {
568 MachineInstr *MI = &*I;
569 ++I;
Chris Lattner518bb532010-02-09 19:54:29 +0000570 if (MI->isPHI()) {
Evan Cheng111e7622009-12-03 08:43:53 +0000571 // Replace the uses of the def of the PHI with the register coming
572 // from PredBB.
Evan Cheng3466f132009-12-15 01:44:10 +0000573 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000574 } else {
575 // Replace def of virtual registers with new registers, and update
576 // uses with PHI source register or the new registers.
577 DuplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap);
Evan Cheng111e7622009-12-03 08:43:53 +0000578 }
Bob Wilson15acadd2009-11-26 00:32:21 +0000579 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000580 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
Evan Cheng3466f132009-12-15 01:44:10 +0000581 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +0000582 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
583 TII->get(TargetOpcode::COPY),
584 CopyInfos[i].first).addReg(CopyInfos[i].second));
Evan Cheng75eb5352009-12-07 10:15:19 +0000585 }
Bob Wilson15acadd2009-11-26 00:32:21 +0000586 NumInstrDups += TailBB->size() - 1; // subtract one for removed branch
587
588 // Update the CFG.
589 PredBB->removeSuccessor(PredBB->succ_begin());
590 assert(PredBB->succ_empty() &&
591 "TailDuplicate called on block with multiple successors!");
592 for (MachineBasicBlock::succ_iterator I = TailBB->succ_begin(),
Evan Cheng79fc6f42009-12-04 09:42:45 +0000593 E = TailBB->succ_end(); I != E; ++I)
594 PredBB->addSuccessor(*I);
Bob Wilson15acadd2009-11-26 00:32:21 +0000595
596 Changed = true;
597 ++NumTailDups;
598 }
599
600 // If TailBB was duplicated into all its predecessors except for the prior
601 // block, which falls through unconditionally, move the contents of this
602 // block into the prior block.
Evan Cheng79fc6f42009-12-04 09:42:45 +0000603 MachineBasicBlock *PrevBB = prior(MachineFunction::iterator(TailBB));
Bob Wilson15acadd2009-11-26 00:32:21 +0000604 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
605 SmallVector<MachineOperand, 4> PriorCond;
Bob Wilson15acadd2009-11-26 00:32:21 +0000606 // This has to check PrevBB->succ_size() because EH edges are ignored by
607 // AnalyzeBranch.
Rafael Espindolaa899b222011-06-09 21:43:25 +0000608 if (PrevBB->succ_size() == 1 &&
609 !TII->AnalyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) &&
610 PriorCond.empty() && !PriorTBB && TailBB->pred_size() == 1 &&
Bob Wilson15acadd2009-11-26 00:32:21 +0000611 !TailBB->hasAddressTaken()) {
David Greene00dec1b2010-01-05 01:25:15 +0000612 DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
Bob Wilson15acadd2009-11-26 00:32:21 +0000613 << "From MBB: " << *TailBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000614 if (PreRegAlloc) {
615 DenseMap<unsigned, unsigned> LocalVRMap;
Evan Cheng3466f132009-12-15 01:44:10 +0000616 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000617 MachineBasicBlock::iterator I = TailBB->begin();
618 // Process PHI instructions first.
Chris Lattner518bb532010-02-09 19:54:29 +0000619 while (I != TailBB->end() && I->isPHI()) {
Evan Cheng79fc6f42009-12-04 09:42:45 +0000620 // Replace the uses of the def of the PHI with the register coming
621 // from PredBB.
622 MachineInstr *MI = &*I++;
Evan Cheng3466f132009-12-15 01:44:10 +0000623 ProcessPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000624 if (MI->getParent())
625 MI->eraseFromParent();
626 }
627
628 // Now copy the non-PHI instructions.
629 while (I != TailBB->end()) {
630 // Replace def of virtual registers with new registers, and update
631 // uses with PHI source register or the new registers.
632 MachineInstr *MI = &*I++;
633 DuplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap);
634 MI->eraseFromParent();
635 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000636 MachineBasicBlock::iterator Loc = PrevBB->getFirstTerminator();
Evan Cheng3466f132009-12-15 01:44:10 +0000637 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +0000638 Copies.push_back(BuildMI(*PrevBB, Loc, DebugLoc(),
639 TII->get(TargetOpcode::COPY),
640 CopyInfos[i].first)
641 .addReg(CopyInfos[i].second));
Evan Cheng75eb5352009-12-07 10:15:19 +0000642 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000643 } else {
644 // No PHIs to worry about, just splice the instructions over.
645 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
646 }
647 PrevBB->removeSuccessor(PrevBB->succ_begin());
648 assert(PrevBB->succ_empty());
649 PrevBB->transferSuccessors(TailBB);
Evan Cheng75eb5352009-12-07 10:15:19 +0000650 TDBBs.push_back(PrevBB);
Bob Wilson15acadd2009-11-26 00:32:21 +0000651 Changed = true;
652 }
653
654 return Changed;
655}
656
657/// RemoveDeadBlock - Remove the specified dead machine basic block from the
658/// function, updating the CFG.
Bob Wilson2d521e52009-11-26 21:38:41 +0000659void TailDuplicatePass::RemoveDeadBlock(MachineBasicBlock *MBB) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000660 assert(MBB->pred_empty() && "MBB must be dead!");
David Greene00dec1b2010-01-05 01:25:15 +0000661 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
Bob Wilson15acadd2009-11-26 00:32:21 +0000662
663 // Remove all successors.
664 while (!MBB->succ_empty())
665 MBB->removeSuccessor(MBB->succ_end()-1);
666
Bob Wilson15acadd2009-11-26 00:32:21 +0000667 // Remove the block.
668 MBB->eraseFromParent();
669}
670