blob: ea62b191c4d66bda397284800dd66f28e6dac973 [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);
Evan Cheng75eb5352009-12-07 10:15:19 +000094 bool TailDuplicate(MachineBasicBlock *TailBB, MachineFunction &MF,
Evan Cheng3466f132009-12-15 01:44:10 +000095 SmallVector<MachineBasicBlock*, 8> &TDBBs,
96 SmallVector<MachineInstr*, 16> &Copies);
Bob Wilson15acadd2009-11-26 00:32:21 +000097 void RemoveDeadBlock(MachineBasicBlock *MBB);
98 };
99
Bob Wilson2d521e52009-11-26 21:38:41 +0000100 char TailDuplicatePass::ID = 0;
Bob Wilson15acadd2009-11-26 00:32:21 +0000101}
102
Evan Cheng79fc6f42009-12-04 09:42:45 +0000103FunctionPass *llvm::createTailDuplicatePass(bool PreRegAlloc) {
104 return new TailDuplicatePass(PreRegAlloc);
Bob Wilson15acadd2009-11-26 00:32:21 +0000105}
106
Bob Wilson2d521e52009-11-26 21:38:41 +0000107bool TailDuplicatePass::runOnMachineFunction(MachineFunction &MF) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000108 TII = MF.getTarget().getInstrInfo();
Evan Cheng111e7622009-12-03 08:43:53 +0000109 MRI = &MF.getRegInfo();
Bob Wilson15acadd2009-11-26 00:32:21 +0000110 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
111
112 bool MadeChange = false;
Jakob Stoklund Olesen057d5392010-01-15 19:59:57 +0000113 while (TailDuplicateBlocks(MF))
114 MadeChange = true;
Bob Wilson15acadd2009-11-26 00:32:21 +0000115
116 return MadeChange;
117}
118
Evan Cheng75eb5352009-12-07 10:15:19 +0000119static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
120 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
121 MachineBasicBlock *MBB = I;
122 SmallSetVector<MachineBasicBlock*, 8> Preds(MBB->pred_begin(),
123 MBB->pred_end());
124 MachineBasicBlock::iterator MI = MBB->begin();
125 while (MI != MBB->end()) {
Chris Lattner518bb532010-02-09 19:54:29 +0000126 if (!MI->isPHI())
Evan Cheng75eb5352009-12-07 10:15:19 +0000127 break;
128 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
129 PE = Preds.end(); PI != PE; ++PI) {
130 MachineBasicBlock *PredBB = *PI;
131 bool Found = false;
132 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
133 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
134 if (PHIBB == PredBB) {
135 Found = true;
136 break;
137 }
138 }
139 if (!Found) {
David Greene00dec1b2010-01-05 01:25:15 +0000140 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
141 dbgs() << " missing input from predecessor BB#"
Evan Cheng75eb5352009-12-07 10:15:19 +0000142 << PredBB->getNumber() << '\n';
143 llvm_unreachable(0);
144 }
145 }
146
147 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
148 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
149 if (CheckExtra && !Preds.count(PHIBB)) {
150 // This is not a hard error.
David Greene00dec1b2010-01-05 01:25:15 +0000151 dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber()
Evan Cheng75eb5352009-12-07 10:15:19 +0000152 << ": " << *MI;
David Greene00dec1b2010-01-05 01:25:15 +0000153 dbgs() << " extra input from predecessor BB#"
Evan Cheng75eb5352009-12-07 10:15:19 +0000154 << PHIBB->getNumber() << '\n';
155 }
156 if (PHIBB->getNumber() < 0) {
David Greene00dec1b2010-01-05 01:25:15 +0000157 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
158 dbgs() << " non-existing BB#" << PHIBB->getNumber() << '\n';
Evan Cheng75eb5352009-12-07 10:15:19 +0000159 llvm_unreachable(0);
160 }
161 }
162 ++MI;
163 }
164 }
165}
166
Bob Wilson15acadd2009-11-26 00:32:21 +0000167/// TailDuplicateBlocks - Look for small blocks that are unconditionally
168/// branched to and do not fall through. Tail-duplicate their instructions
169/// into their predecessors to eliminate (dynamic) branches.
Bob Wilson2d521e52009-11-26 21:38:41 +0000170bool TailDuplicatePass::TailDuplicateBlocks(MachineFunction &MF) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000171 bool MadeChange = false;
172
Evan Cheng75eb5352009-12-07 10:15:19 +0000173 if (PreRegAlloc && TailDupVerify) {
David Greene00dec1b2010-01-05 01:25:15 +0000174 DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
Evan Cheng75eb5352009-12-07 10:15:19 +0000175 VerifyPHIs(MF, true);
176 }
177
178 SmallVector<MachineInstr*, 8> NewPHIs;
179 MachineSSAUpdater SSAUpdate(MF, &NewPHIs);
180
Bob Wilson15acadd2009-11-26 00:32:21 +0000181 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
182 MachineBasicBlock *MBB = I++;
183
Evan Cheng75eb5352009-12-07 10:15:19 +0000184 if (NumTails == TailDupLimit)
185 break;
186
Bob Wilson15acadd2009-11-26 00:32:21 +0000187 // Only duplicate blocks that end with unconditional branches.
188 if (MBB->canFallThrough())
189 continue;
190
Evan Cheng75eb5352009-12-07 10:15:19 +0000191 // Save the successors list.
192 SmallSetVector<MachineBasicBlock*, 8> Succs(MBB->succ_begin(),
193 MBB->succ_end());
Bob Wilson15acadd2009-11-26 00:32:21 +0000194
Evan Cheng75eb5352009-12-07 10:15:19 +0000195 SmallVector<MachineBasicBlock*, 8> TDBBs;
Evan Cheng3466f132009-12-15 01:44:10 +0000196 SmallVector<MachineInstr*, 16> Copies;
197 if (TailDuplicate(MBB, MF, TDBBs, Copies)) {
Evan Cheng75eb5352009-12-07 10:15:19 +0000198 ++NumTails;
199
200 // TailBB's immediate successors are now successors of those predecessors
201 // which duplicated TailBB. Add the predecessors as sources to the PHI
202 // instructions.
203 bool isDead = MBB->pred_empty();
204 if (PreRegAlloc)
205 UpdateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
206
207 // If it is dead, remove it.
208 if (isDead) {
209 NumInstrDups -= MBB->size();
210 RemoveDeadBlock(MBB);
211 ++NumDeadBlocks;
212 }
213
214 // Update SSA form.
215 if (!SSAUpdateVRs.empty()) {
216 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
217 unsigned VReg = SSAUpdateVRs[i];
218 SSAUpdate.Initialize(VReg);
219
220 // If the original definition is still around, add it as an available
221 // value.
222 MachineInstr *DefMI = MRI->getVRegDef(VReg);
223 MachineBasicBlock *DefBB = 0;
224 if (DefMI) {
225 DefBB = DefMI->getParent();
226 SSAUpdate.AddAvailableValue(DefBB, VReg);
227 }
228
229 // Add the new vregs as available values.
230 DenseMap<unsigned, AvailableValsTy>::iterator LI =
231 SSAUpdateVals.find(VReg);
232 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
233 MachineBasicBlock *SrcBB = LI->second[j].first;
234 unsigned SrcReg = LI->second[j].second;
235 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
236 }
237
238 // Rewrite uses that are outside of the original def's block.
239 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
240 while (UI != MRI->use_end()) {
241 MachineOperand &UseMO = UI.getOperand();
242 MachineInstr *UseMI = &*UI;
243 ++UI;
244 if (UseMI->getParent() == DefBB)
245 continue;
246 SSAUpdate.RewriteUse(UseMO);
Evan Cheng75eb5352009-12-07 10:15:19 +0000247 }
248 }
249
Rafael Espindola0cdca082011-06-08 14:13:31 +0000250 NumAddedPHIs += NewPHIs.size();
Evan Cheng75eb5352009-12-07 10:15:19 +0000251 SSAUpdateVRs.clear();
252 SSAUpdateVals.clear();
253 }
254
Bob Wilsonbfdcf3b2010-01-15 06:29:17 +0000255 // Eliminate some of the copies inserted by tail duplication to maintain
Evan Cheng3466f132009-12-15 01:44:10 +0000256 // SSA form.
257 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
258 MachineInstr *Copy = Copies[i];
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000259 if (!Copy->isCopy())
260 continue;
261 unsigned Dst = Copy->getOperand(0).getReg();
262 unsigned Src = Copy->getOperand(1).getReg();
263 MachineRegisterInfo::use_iterator UI = MRI->use_begin(Src);
264 if (++UI == MRI->use_end()) {
265 // Copy is the only use. Do trivial copy propagation here.
266 MRI->replaceRegWith(Dst, Src);
267 Copy->eraseFromParent();
Evan Cheng3466f132009-12-15 01:44:10 +0000268 }
269 }
270
Evan Cheng75eb5352009-12-07 10:15:19 +0000271 if (PreRegAlloc && TailDupVerify)
272 VerifyPHIs(MF, false);
Bob Wilson15acadd2009-11-26 00:32:21 +0000273 MadeChange = true;
Bob Wilson15acadd2009-11-26 00:32:21 +0000274 }
275 }
Evan Cheng111e7622009-12-03 08:43:53 +0000276
Bob Wilson15acadd2009-11-26 00:32:21 +0000277 return MadeChange;
278}
279
Evan Cheng111e7622009-12-03 08:43:53 +0000280static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
281 const MachineRegisterInfo *MRI) {
282 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
283 UE = MRI->use_end(); UI != UE; ++UI) {
284 MachineInstr *UseMI = &*UI;
285 if (UseMI->getParent() != BB)
286 return true;
287 }
288 return false;
289}
290
291static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
292 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
293 if (MI->getOperand(i+1).getMBB() == SrcBB)
294 return i;
295 return 0;
296}
297
298/// AddSSAUpdateEntry - Add a definition and source virtual registers pair for
299/// SSA update.
Evan Cheng11572ba2009-12-04 19:09:10 +0000300void TailDuplicatePass::AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
301 MachineBasicBlock *BB) {
302 DenseMap<unsigned, AvailableValsTy>::iterator LI= SSAUpdateVals.find(OrigReg);
Evan Cheng111e7622009-12-03 08:43:53 +0000303 if (LI != SSAUpdateVals.end())
Evan Cheng11572ba2009-12-04 19:09:10 +0000304 LI->second.push_back(std::make_pair(BB, NewReg));
Evan Cheng111e7622009-12-03 08:43:53 +0000305 else {
306 AvailableValsTy Vals;
Evan Cheng11572ba2009-12-04 19:09:10 +0000307 Vals.push_back(std::make_pair(BB, NewReg));
Evan Cheng111e7622009-12-03 08:43:53 +0000308 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
309 SSAUpdateVRs.push_back(OrigReg);
310 }
311}
312
Evan Cheng75eb5352009-12-07 10:15:19 +0000313/// ProcessPHI - Process PHI node in TailBB by turning it into a copy in PredBB.
314/// Remember the source register that's contributed by PredBB and update SSA
315/// update map.
Evan Cheng79fc6f42009-12-04 09:42:45 +0000316void TailDuplicatePass::ProcessPHI(MachineInstr *MI,
317 MachineBasicBlock *TailBB,
318 MachineBasicBlock *PredBB,
Evan Cheng75eb5352009-12-07 10:15:19 +0000319 DenseMap<unsigned, unsigned> &LocalVRMap,
320 SmallVector<std::pair<unsigned,unsigned>, 4> &Copies) {
Evan Cheng79fc6f42009-12-04 09:42:45 +0000321 unsigned DefReg = MI->getOperand(0).getReg();
322 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
323 assert(SrcOpIdx && "Unable to find matching PHI source?");
324 unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
Evan Cheng75eb5352009-12-07 10:15:19 +0000325 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000326 LocalVRMap.insert(std::make_pair(DefReg, SrcReg));
Evan Cheng75eb5352009-12-07 10:15:19 +0000327
328 // Insert a copy from source to the end of the block. The def register is the
329 // available value liveout of the block.
330 unsigned NewDef = MRI->createVirtualRegister(RC);
331 Copies.push_back(std::make_pair(NewDef, SrcReg));
Evan Cheng79fc6f42009-12-04 09:42:45 +0000332 if (isDefLiveOut(DefReg, TailBB, MRI))
Evan Cheng75eb5352009-12-07 10:15:19 +0000333 AddSSAUpdateEntry(DefReg, NewDef, PredBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000334
335 // Remove PredBB from the PHI node.
336 MI->RemoveOperand(SrcOpIdx+1);
337 MI->RemoveOperand(SrcOpIdx);
338 if (MI->getNumOperands() == 1)
339 MI->eraseFromParent();
340}
341
342/// DuplicateInstruction - Duplicate a TailBB instruction to PredBB and update
343/// the source operands due to earlier PHI translation.
344void TailDuplicatePass::DuplicateInstruction(MachineInstr *MI,
345 MachineBasicBlock *TailBB,
346 MachineBasicBlock *PredBB,
347 MachineFunction &MF,
348 DenseMap<unsigned, unsigned> &LocalVRMap) {
Jakob Stoklund Olesen30ac0462010-01-06 23:47:07 +0000349 MachineInstr *NewMI = TII->duplicate(MI, MF);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000350 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
351 MachineOperand &MO = NewMI->getOperand(i);
352 if (!MO.isReg())
353 continue;
354 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000355 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng79fc6f42009-12-04 09:42:45 +0000356 continue;
357 if (MO.isDef()) {
358 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
359 unsigned NewReg = MRI->createVirtualRegister(RC);
360 MO.setReg(NewReg);
361 LocalVRMap.insert(std::make_pair(Reg, NewReg));
362 if (isDefLiveOut(Reg, TailBB, MRI))
Evan Cheng11572ba2009-12-04 19:09:10 +0000363 AddSSAUpdateEntry(Reg, NewReg, PredBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000364 } else {
365 DenseMap<unsigned, unsigned>::iterator VI = LocalVRMap.find(Reg);
366 if (VI != LocalVRMap.end())
367 MO.setReg(VI->second);
368 }
369 }
370 PredBB->insert(PredBB->end(), NewMI);
371}
372
373/// UpdateSuccessorsPHIs - After FromBB is tail duplicated into its predecessor
374/// blocks, the successors have gained new predecessors. Update the PHI
375/// instructions in them accordingly.
Evan Cheng75eb5352009-12-07 10:15:19 +0000376void
377TailDuplicatePass::UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
378 SmallVector<MachineBasicBlock*, 8> &TDBBs,
Evan Cheng79fc6f42009-12-04 09:42:45 +0000379 SmallSetVector<MachineBasicBlock*,8> &Succs) {
380 for (SmallSetVector<MachineBasicBlock*, 8>::iterator SI = Succs.begin(),
381 SE = Succs.end(); SI != SE; ++SI) {
382 MachineBasicBlock *SuccBB = *SI;
383 for (MachineBasicBlock::iterator II = SuccBB->begin(), EE = SuccBB->end();
384 II != EE; ++II) {
Chris Lattner518bb532010-02-09 19:54:29 +0000385 if (!II->isPHI())
Evan Cheng79fc6f42009-12-04 09:42:45 +0000386 break;
Evan Cheng75eb5352009-12-07 10:15:19 +0000387 unsigned Idx = 0;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000388 for (unsigned i = 1, e = II->getNumOperands(); i != e; i += 2) {
Evan Cheng75eb5352009-12-07 10:15:19 +0000389 MachineOperand &MO = II->getOperand(i+1);
390 if (MO.getMBB() == FromBB) {
391 Idx = i;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000392 break;
Evan Cheng75eb5352009-12-07 10:15:19 +0000393 }
394 }
395
396 assert(Idx != 0);
397 MachineOperand &MO0 = II->getOperand(Idx);
398 unsigned Reg = MO0.getReg();
399 if (isDead) {
400 // Folded into the previous BB.
401 // There could be duplicate phi source entries. FIXME: Should sdisel
402 // or earlier pass fixed this?
403 for (unsigned i = II->getNumOperands()-2; i != Idx; i -= 2) {
404 MachineOperand &MO = II->getOperand(i+1);
405 if (MO.getMBB() == FromBB) {
406 II->RemoveOperand(i+1);
407 II->RemoveOperand(i);
408 }
409 }
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000410 } else
411 Idx = 0;
412
413 // If Idx is set, the operands at Idx and Idx+1 must be removed.
414 // We reuse the location to avoid expensive RemoveOperand calls.
415
Evan Cheng75eb5352009-12-07 10:15:19 +0000416 DenseMap<unsigned,AvailableValsTy>::iterator LI=SSAUpdateVals.find(Reg);
417 if (LI != SSAUpdateVals.end()) {
418 // This register is defined in the tail block.
Evan Cheng79fc6f42009-12-04 09:42:45 +0000419 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
Evan Cheng11572ba2009-12-04 19:09:10 +0000420 MachineBasicBlock *SrcBB = LI->second[j].first;
421 unsigned SrcReg = LI->second[j].second;
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000422 if (Idx != 0) {
423 II->getOperand(Idx).setReg(SrcReg);
424 II->getOperand(Idx+1).setMBB(SrcBB);
425 Idx = 0;
426 } else {
427 II->addOperand(MachineOperand::CreateReg(SrcReg, false));
428 II->addOperand(MachineOperand::CreateMBB(SrcBB));
429 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000430 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000431 } else {
432 // Live in tail block, must also be live in predecessors.
433 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
434 MachineBasicBlock *SrcBB = TDBBs[j];
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000435 if (Idx != 0) {
436 II->getOperand(Idx).setReg(Reg);
437 II->getOperand(Idx+1).setMBB(SrcBB);
438 Idx = 0;
439 } else {
440 II->addOperand(MachineOperand::CreateReg(Reg, false));
441 II->addOperand(MachineOperand::CreateMBB(SrcBB));
442 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000443 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000444 }
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000445 if (Idx != 0) {
446 II->RemoveOperand(Idx+1);
447 II->RemoveOperand(Idx);
448 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000449 }
450 }
451}
452
Bob Wilson15acadd2009-11-26 00:32:21 +0000453/// TailDuplicate - If it is profitable, duplicate TailBB's contents in each
454/// of its predecessors.
Evan Cheng75eb5352009-12-07 10:15:19 +0000455bool
456TailDuplicatePass::TailDuplicate(MachineBasicBlock *TailBB, MachineFunction &MF,
Evan Cheng3466f132009-12-15 01:44:10 +0000457 SmallVector<MachineBasicBlock*, 8> &TDBBs,
458 SmallVector<MachineInstr*, 16> &Copies) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000459 // Set the limit on the number of instructions to duplicate, with a default
460 // of one less than the tail-merge threshold. When optimizing for size,
461 // duplicate only one, because one branch instruction can be eliminated to
462 // compensate for the duplication.
463 unsigned MaxDuplicateCount;
Jakob Stoklund Olesen83520622011-01-30 20:38:12 +0000464 if (TailDuplicateSize.getNumOccurrences() == 0 &&
465 MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize))
Bob Wilson38582252009-11-30 18:56:45 +0000466 MaxDuplicateCount = 1;
Bob Wilson15acadd2009-11-26 00:32:21 +0000467 else
468 MaxDuplicateCount = TailDuplicateSize;
469
Bob Wilsoncb44b282010-01-16 00:42:25 +0000470 if (PreRegAlloc) {
Evan Chengc3f507f2011-01-29 04:46:23 +0000471 if (TailBB->empty())
472 return false;
473 const TargetInstrDesc &TID = TailBB->back().getDesc();
474 // Pre-regalloc tail duplication hurts compile time and doesn't help
475 // much except for indirect branches and returns.
476 if (!TID.isIndirectBranch() && !TID.isReturn())
Bob Wilsoncb44b282010-01-16 00:42:25 +0000477 return false;
478 // If the target has hardware branch prediction that can handle indirect
479 // branches, duplicating them can often make them predictable when there
480 // are common paths through the code. The limit needs to be high enough
481 // to allow undoing the effects of tail merging and other optimizations
482 // that rearrange the predecessors of the indirect branch.
483 MaxDuplicateCount = 20;
484 }
485
Bob Wilsonbfdcf3b2010-01-15 06:29:17 +0000486 // Don't try to tail-duplicate single-block loops.
487 if (TailBB->isSuccessor(TailBB))
488 return false;
489
Bob Wilson15acadd2009-11-26 00:32:21 +0000490 // Check the instructions in the block to determine whether tail-duplication
491 // is invalid or unlikely to be profitable.
Bob Wilsonf1e01dc2009-12-02 17:15:24 +0000492 unsigned InstrCount = 0;
Bob Wilson15acadd2009-11-26 00:32:21 +0000493 bool HasCall = false;
494 for (MachineBasicBlock::iterator I = TailBB->begin();
Bob Wilsonf1e01dc2009-12-02 17:15:24 +0000495 I != TailBB->end(); ++I) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000496 // Non-duplicable things shouldn't be tail-duplicated.
497 if (I->getDesc().isNotDuplicable()) return false;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000498 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
499 // A return may expand into a lot more instructions (e.g. reload of callee
500 // saved registers) after PEI.
501 if (PreRegAlloc && I->getDesc().isReturn()) return false;
Bob Wilson15acadd2009-11-26 00:32:21 +0000502 // Don't duplicate more than the threshold.
Bob Wilsonf1e01dc2009-12-02 17:15:24 +0000503 if (InstrCount == MaxDuplicateCount) return false;
Bob Wilson15acadd2009-11-26 00:32:21 +0000504 // Remember if we saw a call.
505 if (I->getDesc().isCall()) HasCall = true;
Devang Patelcbe1e312010-03-16 21:02:07 +0000506 if (!I->isPHI() && !I->isDebugValue())
Bob Wilsonf1e01dc2009-12-02 17:15:24 +0000507 InstrCount += 1;
Bob Wilson15acadd2009-11-26 00:32:21 +0000508 }
Evan Chengc8b90e22011-02-04 01:10:12 +0000509 // Don't tail-duplicate calls before register allocation. Calls presents a
510 // barrier to register allocation so duplicating them may end up increasing
511 // spills.
Evan Chengc3f507f2011-01-29 04:46:23 +0000512 if (InstrCount > 1 && (PreRegAlloc && HasCall))
Bob Wilson15acadd2009-11-26 00:32:21 +0000513 return false;
514
David Greene00dec1b2010-01-05 01:25:15 +0000515 DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
Evan Cheng75eb5352009-12-07 10:15:19 +0000516
Bob Wilson15acadd2009-11-26 00:32:21 +0000517 // Iterate through all the unique predecessors and tail-duplicate this
518 // block into them, if possible. Copying the list ahead of time also
519 // avoids trouble with the predecessor list reallocating.
520 bool Changed = false;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000521 SmallSetVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
522 TailBB->pred_end());
Bob Wilson15acadd2009-11-26 00:32:21 +0000523 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
524 PE = Preds.end(); PI != PE; ++PI) {
525 MachineBasicBlock *PredBB = *PI;
526
527 assert(TailBB != PredBB &&
528 "Single-block loop should have been rejected earlier!");
529 if (PredBB->succ_size() > 1) continue;
530
531 MachineBasicBlock *PredTBB, *PredFBB;
532 SmallVector<MachineOperand, 4> PredCond;
533 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
534 continue;
535 if (!PredCond.empty())
536 continue;
537 // EH edges are ignored by AnalyzeBranch.
538 if (PredBB->succ_size() != 1)
539 continue;
540 // Don't duplicate into a fall-through predecessor (at least for now).
541 if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
542 continue;
543
David Greene00dec1b2010-01-05 01:25:15 +0000544 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
Bob Wilson15acadd2009-11-26 00:32:21 +0000545 << "From Succ: " << *TailBB);
546
Evan Cheng75eb5352009-12-07 10:15:19 +0000547 TDBBs.push_back(PredBB);
548
Bob Wilson15acadd2009-11-26 00:32:21 +0000549 // Remove PredBB's unconditional branch.
550 TII->RemoveBranch(*PredBB);
Evan Cheng111e7622009-12-03 08:43:53 +0000551
Bob Wilson15acadd2009-11-26 00:32:21 +0000552 // Clone the contents of TailBB into PredBB.
Evan Cheng111e7622009-12-03 08:43:53 +0000553 DenseMap<unsigned, unsigned> LocalVRMap;
Evan Cheng3466f132009-12-15 01:44:10 +0000554 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
Evan Cheng111e7622009-12-03 08:43:53 +0000555 MachineBasicBlock::iterator I = TailBB->begin();
Evan Cheng79fc6f42009-12-04 09:42:45 +0000556 while (I != TailBB->end()) {
557 MachineInstr *MI = &*I;
558 ++I;
Chris Lattner518bb532010-02-09 19:54:29 +0000559 if (MI->isPHI()) {
Evan Cheng111e7622009-12-03 08:43:53 +0000560 // Replace the uses of the def of the PHI with the register coming
561 // from PredBB.
Evan Cheng3466f132009-12-15 01:44:10 +0000562 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000563 } else {
564 // Replace def of virtual registers with new registers, and update
565 // uses with PHI source register or the new registers.
566 DuplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap);
Evan Cheng111e7622009-12-03 08:43:53 +0000567 }
Bob Wilson15acadd2009-11-26 00:32:21 +0000568 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000569 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
Evan Cheng3466f132009-12-15 01:44:10 +0000570 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +0000571 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
572 TII->get(TargetOpcode::COPY),
573 CopyInfos[i].first).addReg(CopyInfos[i].second));
Evan Cheng75eb5352009-12-07 10:15:19 +0000574 }
Bob Wilson15acadd2009-11-26 00:32:21 +0000575 NumInstrDups += TailBB->size() - 1; // subtract one for removed branch
576
577 // Update the CFG.
578 PredBB->removeSuccessor(PredBB->succ_begin());
579 assert(PredBB->succ_empty() &&
580 "TailDuplicate called on block with multiple successors!");
581 for (MachineBasicBlock::succ_iterator I = TailBB->succ_begin(),
Evan Cheng79fc6f42009-12-04 09:42:45 +0000582 E = TailBB->succ_end(); I != E; ++I)
583 PredBB->addSuccessor(*I);
Bob Wilson15acadd2009-11-26 00:32:21 +0000584
585 Changed = true;
586 ++NumTailDups;
587 }
588
589 // If TailBB was duplicated into all its predecessors except for the prior
590 // block, which falls through unconditionally, move the contents of this
591 // block into the prior block.
Evan Cheng79fc6f42009-12-04 09:42:45 +0000592 MachineBasicBlock *PrevBB = prior(MachineFunction::iterator(TailBB));
Bob Wilson15acadd2009-11-26 00:32:21 +0000593 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
594 SmallVector<MachineOperand, 4> PriorCond;
595 bool PriorUnAnalyzable =
Evan Cheng79fc6f42009-12-04 09:42:45 +0000596 TII->AnalyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true);
Bob Wilson15acadd2009-11-26 00:32:21 +0000597 // This has to check PrevBB->succ_size() because EH edges are ignored by
598 // AnalyzeBranch.
599 if (!PriorUnAnalyzable && PriorCond.empty() && !PriorTBB &&
Evan Cheng79fc6f42009-12-04 09:42:45 +0000600 TailBB->pred_size() == 1 && PrevBB->succ_size() == 1 &&
Bob Wilson15acadd2009-11-26 00:32:21 +0000601 !TailBB->hasAddressTaken()) {
David Greene00dec1b2010-01-05 01:25:15 +0000602 DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
Bob Wilson15acadd2009-11-26 00:32:21 +0000603 << "From MBB: " << *TailBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000604 if (PreRegAlloc) {
605 DenseMap<unsigned, unsigned> LocalVRMap;
Evan Cheng3466f132009-12-15 01:44:10 +0000606 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000607 MachineBasicBlock::iterator I = TailBB->begin();
608 // Process PHI instructions first.
Chris Lattner518bb532010-02-09 19:54:29 +0000609 while (I != TailBB->end() && I->isPHI()) {
Evan Cheng79fc6f42009-12-04 09:42:45 +0000610 // Replace the uses of the def of the PHI with the register coming
611 // from PredBB.
612 MachineInstr *MI = &*I++;
Evan Cheng3466f132009-12-15 01:44:10 +0000613 ProcessPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000614 if (MI->getParent())
615 MI->eraseFromParent();
616 }
617
618 // Now copy the non-PHI instructions.
619 while (I != TailBB->end()) {
620 // Replace def of virtual registers with new registers, and update
621 // uses with PHI source register or the new registers.
622 MachineInstr *MI = &*I++;
623 DuplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap);
624 MI->eraseFromParent();
625 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000626 MachineBasicBlock::iterator Loc = PrevBB->getFirstTerminator();
Evan Cheng3466f132009-12-15 01:44:10 +0000627 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +0000628 Copies.push_back(BuildMI(*PrevBB, Loc, DebugLoc(),
629 TII->get(TargetOpcode::COPY),
630 CopyInfos[i].first)
631 .addReg(CopyInfos[i].second));
Evan Cheng75eb5352009-12-07 10:15:19 +0000632 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000633 } else {
634 // No PHIs to worry about, just splice the instructions over.
635 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
636 }
637 PrevBB->removeSuccessor(PrevBB->succ_begin());
638 assert(PrevBB->succ_empty());
639 PrevBB->transferSuccessors(TailBB);
Evan Cheng75eb5352009-12-07 10:15:19 +0000640 TDBBs.push_back(PrevBB);
Bob Wilson15acadd2009-11-26 00:32:21 +0000641 Changed = true;
642 }
643
644 return Changed;
645}
646
647/// RemoveDeadBlock - Remove the specified dead machine basic block from the
648/// function, updating the CFG.
Bob Wilson2d521e52009-11-26 21:38:41 +0000649void TailDuplicatePass::RemoveDeadBlock(MachineBasicBlock *MBB) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000650 assert(MBB->pred_empty() && "MBB must be dead!");
David Greene00dec1b2010-01-05 01:25:15 +0000651 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
Bob Wilson15acadd2009-11-26 00:32:21 +0000652
653 // Remove all successors.
654 while (!MBB->succ_empty())
655 MBB->removeSuccessor(MBB->succ_end()-1);
656
Bob Wilson15acadd2009-11-26 00:32:21 +0000657 // Remove the block.
658 MBB->eraseFromParent();
659}
660