blob: 031377b36b5435aef63f5f083acf975e65cf0638 [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"
Jakob Stoklund Olesenc66d3602011-08-09 23:49:21 +000028#include "llvm/ADT/DenseSet.h"
Bob Wilson15acadd2009-11-26 00:32:21 +000029#include "llvm/ADT/SmallSet.h"
30#include "llvm/ADT/SetVector.h"
31#include "llvm/ADT/Statistic.h"
32using namespace llvm;
33
Evan Cheng75eb5352009-12-07 10:15:19 +000034STATISTIC(NumTails , "Number of tails duplicated");
Bob Wilson15acadd2009-11-26 00:32:21 +000035STATISTIC(NumTailDups , "Number of tail duplicated blocks");
36STATISTIC(NumInstrDups , "Additional instructions due to tail duplication");
37STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
Rafael Espindola0cdca082011-06-08 14:13:31 +000038STATISTIC(NumAddedPHIs , "Number of phis added");
Bob Wilson15acadd2009-11-26 00:32:21 +000039
40// Heuristic for tail duplication.
41static cl::opt<unsigned>
42TailDuplicateSize("tail-dup-size",
43 cl::desc("Maximum instructions to consider tail duplicating"),
44 cl::init(2), cl::Hidden);
45
Evan Cheng75eb5352009-12-07 10:15:19 +000046static cl::opt<bool>
47TailDupVerify("tail-dup-verify",
48 cl::desc("Verify sanity of PHI instructions during taildup"),
49 cl::init(false), cl::Hidden);
50
51static cl::opt<unsigned>
52TailDupLimit("tail-dup-limit", cl::init(~0U), cl::Hidden);
53
Evan Cheng11572ba2009-12-04 19:09:10 +000054typedef std::vector<std::pair<MachineBasicBlock*,unsigned> > AvailableValsTy;
Evan Cheng111e7622009-12-03 08:43:53 +000055
Bob Wilson15acadd2009-11-26 00:32:21 +000056namespace {
Bob Wilson2d521e52009-11-26 21:38:41 +000057 /// TailDuplicatePass - Perform tail duplication.
58 class TailDuplicatePass : public MachineFunctionPass {
Evan Cheng79fc6f42009-12-04 09:42:45 +000059 bool PreRegAlloc;
Bob Wilson15acadd2009-11-26 00:32:21 +000060 const TargetInstrInfo *TII;
61 MachineModuleInfo *MMI;
Evan Cheng111e7622009-12-03 08:43:53 +000062 MachineRegisterInfo *MRI;
63
64 // SSAUpdateVRs - A list of virtual registers for which to update SSA form.
65 SmallVector<unsigned, 16> SSAUpdateVRs;
66
67 // SSAUpdateVals - For each virtual register in SSAUpdateVals keep a list of
68 // source virtual registers.
69 DenseMap<unsigned, AvailableValsTy> SSAUpdateVals;
Bob Wilson15acadd2009-11-26 00:32:21 +000070
71 public:
72 static char ID;
Evan Cheng79fc6f42009-12-04 09:42:45 +000073 explicit TailDuplicatePass(bool PreRA) :
Owen Anderson90c579d2010-08-06 18:33:48 +000074 MachineFunctionPass(ID), PreRegAlloc(PreRA) {}
Bob Wilson15acadd2009-11-26 00:32:21 +000075
76 virtual bool runOnMachineFunction(MachineFunction &MF);
77 virtual const char *getPassName() const { return "Tail Duplication"; }
78
79 private:
Evan Cheng11572ba2009-12-04 19:09:10 +000080 void AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
81 MachineBasicBlock *BB);
Evan Cheng79fc6f42009-12-04 09:42:45 +000082 void ProcessPHI(MachineInstr *MI, MachineBasicBlock *TailBB,
83 MachineBasicBlock *PredBB,
Evan Cheng75eb5352009-12-07 10:15:19 +000084 DenseMap<unsigned, unsigned> &LocalVRMap,
Rafael Espindola0f28c3f2011-06-09 22:53:47 +000085 SmallVector<std::pair<unsigned,unsigned>, 4> &Copies,
Rafael Espindola689d7d52011-06-09 23:22:56 +000086 const DenseSet<unsigned> &UsedByPhi,
87 bool Remove);
Evan Cheng79fc6f42009-12-04 09:42:45 +000088 void DuplicateInstruction(MachineInstr *MI,
89 MachineBasicBlock *TailBB,
90 MachineBasicBlock *PredBB,
91 MachineFunction &MF,
Rafael Espindola0f28c3f2011-06-09 22:53:47 +000092 DenseMap<unsigned, unsigned> &LocalVRMap,
93 const DenseSet<unsigned> &UsedByPhi);
Evan Cheng75eb5352009-12-07 10:15:19 +000094 void UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
95 SmallVector<MachineBasicBlock*, 8> &TDBBs,
96 SmallSetVector<MachineBasicBlock*, 8> &Succs);
Bob Wilson15acadd2009-11-26 00:32:21 +000097 bool TailDuplicateBlocks(MachineFunction &MF);
Rafael Espindola54c25622011-06-09 19:54:42 +000098 bool shouldTailDuplicate(const MachineFunction &MF,
Rafael Espindola9dbbd872011-06-23 03:41:29 +000099 bool IsSimple, MachineBasicBlock &TailBB);
Rafael Espindola275c1f92011-06-20 04:16:35 +0000100 bool isSimpleBB(MachineBasicBlock *TailBB);
Rafael Espindola40179bf2011-06-24 15:50:56 +0000101 bool canCompletelyDuplicateBB(MachineBasicBlock &BB);
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000102 bool duplicateSimpleBB(MachineBasicBlock *TailBB,
Rafael Espindola275c1f92011-06-20 04:16:35 +0000103 SmallVector<MachineBasicBlock*, 8> &TDBBs,
104 const DenseSet<unsigned> &RegsUsedByPhi,
105 SmallVector<MachineInstr*, 16> &Copies);
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000106 bool TailDuplicate(MachineBasicBlock *TailBB,
107 bool IsSimple,
108 MachineFunction &MF,
Evan Cheng3466f132009-12-15 01:44:10 +0000109 SmallVector<MachineBasicBlock*, 8> &TDBBs,
110 SmallVector<MachineInstr*, 16> &Copies);
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000111 bool TailDuplicateAndUpdate(MachineBasicBlock *MBB,
112 bool IsSimple,
113 MachineFunction &MF);
114
Bob Wilson15acadd2009-11-26 00:32:21 +0000115 void RemoveDeadBlock(MachineBasicBlock *MBB);
116 };
117
Bob Wilson2d521e52009-11-26 21:38:41 +0000118 char TailDuplicatePass::ID = 0;
Bob Wilson15acadd2009-11-26 00:32:21 +0000119}
120
Evan Cheng79fc6f42009-12-04 09:42:45 +0000121FunctionPass *llvm::createTailDuplicatePass(bool PreRegAlloc) {
122 return new TailDuplicatePass(PreRegAlloc);
Bob Wilson15acadd2009-11-26 00:32:21 +0000123}
124
Bob Wilson2d521e52009-11-26 21:38:41 +0000125bool TailDuplicatePass::runOnMachineFunction(MachineFunction &MF) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000126 TII = MF.getTarget().getInstrInfo();
Evan Cheng111e7622009-12-03 08:43:53 +0000127 MRI = &MF.getRegInfo();
Bob Wilson15acadd2009-11-26 00:32:21 +0000128 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
129
130 bool MadeChange = false;
Jakob Stoklund Olesen057d5392010-01-15 19:59:57 +0000131 while (TailDuplicateBlocks(MF))
132 MadeChange = true;
Bob Wilson15acadd2009-11-26 00:32:21 +0000133
134 return MadeChange;
135}
136
Evan Cheng75eb5352009-12-07 10:15:19 +0000137static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
138 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
139 MachineBasicBlock *MBB = I;
140 SmallSetVector<MachineBasicBlock*, 8> Preds(MBB->pred_begin(),
141 MBB->pred_end());
142 MachineBasicBlock::iterator MI = MBB->begin();
143 while (MI != MBB->end()) {
Chris Lattner518bb532010-02-09 19:54:29 +0000144 if (!MI->isPHI())
Evan Cheng75eb5352009-12-07 10:15:19 +0000145 break;
146 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
147 PE = Preds.end(); PI != PE; ++PI) {
148 MachineBasicBlock *PredBB = *PI;
149 bool Found = false;
150 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
151 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
152 if (PHIBB == PredBB) {
153 Found = true;
154 break;
155 }
156 }
157 if (!Found) {
David Greene00dec1b2010-01-05 01:25:15 +0000158 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
159 dbgs() << " missing input from predecessor BB#"
Evan Cheng75eb5352009-12-07 10:15:19 +0000160 << PredBB->getNumber() << '\n';
161 llvm_unreachable(0);
162 }
163 }
164
165 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
166 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
167 if (CheckExtra && !Preds.count(PHIBB)) {
David Greene00dec1b2010-01-05 01:25:15 +0000168 dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber()
Evan Cheng75eb5352009-12-07 10:15:19 +0000169 << ": " << *MI;
David Greene00dec1b2010-01-05 01:25:15 +0000170 dbgs() << " extra input from predecessor BB#"
Evan Cheng75eb5352009-12-07 10:15:19 +0000171 << PHIBB->getNumber() << '\n';
Rafael Espindolad3f4eea2011-06-09 23:55:56 +0000172 llvm_unreachable(0);
Evan Cheng75eb5352009-12-07 10:15:19 +0000173 }
174 if (PHIBB->getNumber() < 0) {
David Greene00dec1b2010-01-05 01:25:15 +0000175 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
176 dbgs() << " non-existing BB#" << PHIBB->getNumber() << '\n';
Evan Cheng75eb5352009-12-07 10:15:19 +0000177 llvm_unreachable(0);
178 }
179 }
180 ++MI;
181 }
182 }
183}
184
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000185/// TailDuplicateAndUpdate - Tail duplicate the block and cleanup.
186bool
187TailDuplicatePass::TailDuplicateAndUpdate(MachineBasicBlock *MBB,
188 bool IsSimple,
189 MachineFunction &MF) {
190 // Save the successors list.
191 SmallSetVector<MachineBasicBlock*, 8> Succs(MBB->succ_begin(),
192 MBB->succ_end());
193
194 SmallVector<MachineBasicBlock*, 8> TDBBs;
195 SmallVector<MachineInstr*, 16> Copies;
196 if (!TailDuplicate(MBB, IsSimple, MF, TDBBs, Copies))
197 return false;
198
199 ++NumTails;
200
201 SmallVector<MachineInstr*, 8> NewPHIs;
202 MachineSSAUpdater SSAUpdate(MF, &NewPHIs);
203
204 // TailBB's immediate successors are now successors of those predecessors
205 // which duplicated TailBB. Add the predecessors as sources to the PHI
206 // instructions.
207 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
208 if (PreRegAlloc)
209 UpdateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
210
211 // If it is dead, remove it.
212 if (isDead) {
213 NumInstrDups -= MBB->size();
214 RemoveDeadBlock(MBB);
215 ++NumDeadBlocks;
216 }
217
218 // Update SSA form.
219 if (!SSAUpdateVRs.empty()) {
220 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
221 unsigned VReg = SSAUpdateVRs[i];
222 SSAUpdate.Initialize(VReg);
223
224 // If the original definition is still around, add it as an available
225 // value.
226 MachineInstr *DefMI = MRI->getVRegDef(VReg);
227 MachineBasicBlock *DefBB = 0;
228 if (DefMI) {
229 DefBB = DefMI->getParent();
230 SSAUpdate.AddAvailableValue(DefBB, VReg);
231 }
232
233 // Add the new vregs as available values.
234 DenseMap<unsigned, AvailableValsTy>::iterator LI =
235 SSAUpdateVals.find(VReg);
236 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
237 MachineBasicBlock *SrcBB = LI->second[j].first;
238 unsigned SrcReg = LI->second[j].second;
239 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
240 }
241
242 // Rewrite uses that are outside of the original def's block.
243 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
244 while (UI != MRI->use_end()) {
245 MachineOperand &UseMO = UI.getOperand();
246 MachineInstr *UseMI = &*UI;
247 ++UI;
248 if (UseMI->isDebugValue()) {
249 // SSAUpdate can replace the use with an undef. That creates
250 // a debug instruction that is a kill.
251 // FIXME: Should it SSAUpdate job to delete debug instructions
252 // instead of replacing the use with undef?
253 UseMI->eraseFromParent();
254 continue;
255 }
256 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
257 continue;
258 SSAUpdate.RewriteUse(UseMO);
259 }
260 }
261
262 SSAUpdateVRs.clear();
263 SSAUpdateVals.clear();
264 }
265
266 // Eliminate some of the copies inserted by tail duplication to maintain
267 // SSA form.
268 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
269 MachineInstr *Copy = Copies[i];
270 if (!Copy->isCopy())
271 continue;
272 unsigned Dst = Copy->getOperand(0).getReg();
273 unsigned Src = Copy->getOperand(1).getReg();
274 MachineRegisterInfo::use_iterator UI = MRI->use_begin(Src);
275 if (++UI == MRI->use_end()) {
276 // Copy is the only use. Do trivial copy propagation here.
277 MRI->replaceRegWith(Dst, Src);
278 Copy->eraseFromParent();
279 }
280 }
281
282 if (NewPHIs.size())
283 NumAddedPHIs += NewPHIs.size();
284
285 return true;
286}
287
Bob Wilson15acadd2009-11-26 00:32:21 +0000288/// TailDuplicateBlocks - Look for small blocks that are unconditionally
289/// branched to and do not fall through. Tail-duplicate their instructions
290/// into their predecessors to eliminate (dynamic) branches.
Bob Wilson2d521e52009-11-26 21:38:41 +0000291bool TailDuplicatePass::TailDuplicateBlocks(MachineFunction &MF) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000292 bool MadeChange = false;
293
Evan Cheng75eb5352009-12-07 10:15:19 +0000294 if (PreRegAlloc && TailDupVerify) {
David Greene00dec1b2010-01-05 01:25:15 +0000295 DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
Evan Cheng75eb5352009-12-07 10:15:19 +0000296 VerifyPHIs(MF, true);
297 }
298
Bob Wilson15acadd2009-11-26 00:32:21 +0000299 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
300 MachineBasicBlock *MBB = I++;
301
Evan Cheng75eb5352009-12-07 10:15:19 +0000302 if (NumTails == TailDupLimit)
303 break;
304
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000305 bool IsSimple = isSimpleBB(MBB);
Bob Wilson15acadd2009-11-26 00:32:21 +0000306
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000307 if (!shouldTailDuplicate(MF, IsSimple, *MBB))
Rafael Espindolac0af3522011-07-04 00:13:36 +0000308 continue;
Evan Cheng75eb5352009-12-07 10:15:19 +0000309
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000310 MadeChange |= TailDuplicateAndUpdate(MBB, IsSimple, MF);
Bob Wilson15acadd2009-11-26 00:32:21 +0000311 }
Rafael Espindolac0af3522011-07-04 00:13:36 +0000312
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000313 if (PreRegAlloc && TailDupVerify)
314 VerifyPHIs(MF, false);
Evan Cheng111e7622009-12-03 08:43:53 +0000315
Bob Wilson15acadd2009-11-26 00:32:21 +0000316 return MadeChange;
317}
318
Evan Cheng111e7622009-12-03 08:43:53 +0000319static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
320 const MachineRegisterInfo *MRI) {
321 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
322 UE = MRI->use_end(); UI != UE; ++UI) {
323 MachineInstr *UseMI = &*UI;
Rafael Espindoladb3983b2011-06-17 13:59:43 +0000324 if (UseMI->isDebugValue())
325 continue;
Evan Cheng111e7622009-12-03 08:43:53 +0000326 if (UseMI->getParent() != BB)
327 return true;
328 }
329 return false;
330}
331
332static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
333 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
334 if (MI->getOperand(i+1).getMBB() == SrcBB)
335 return i;
336 return 0;
337}
338
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000339
340// Remember which registers are used by phis in this block. This is
341// used to determine which registers are liveout while modifying the
342// block (which is why we need to copy the information).
343static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
Rafael Espindola33b46582011-06-10 21:01:53 +0000344 DenseSet<unsigned> *UsedByPhi) {
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000345 for(MachineBasicBlock::const_iterator I = BB.begin(), E = BB.end();
346 I != E; ++I) {
347 const MachineInstr &MI = *I;
348 if (!MI.isPHI())
349 break;
350 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
351 unsigned SrcReg = MI.getOperand(i).getReg();
352 UsedByPhi->insert(SrcReg);
353 }
354 }
355}
356
Evan Cheng111e7622009-12-03 08:43:53 +0000357/// AddSSAUpdateEntry - Add a definition and source virtual registers pair for
358/// SSA update.
Evan Cheng11572ba2009-12-04 19:09:10 +0000359void TailDuplicatePass::AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
360 MachineBasicBlock *BB) {
361 DenseMap<unsigned, AvailableValsTy>::iterator LI= SSAUpdateVals.find(OrigReg);
Evan Cheng111e7622009-12-03 08:43:53 +0000362 if (LI != SSAUpdateVals.end())
Evan Cheng11572ba2009-12-04 19:09:10 +0000363 LI->second.push_back(std::make_pair(BB, NewReg));
Evan Cheng111e7622009-12-03 08:43:53 +0000364 else {
365 AvailableValsTy Vals;
Evan Cheng11572ba2009-12-04 19:09:10 +0000366 Vals.push_back(std::make_pair(BB, NewReg));
Evan Cheng111e7622009-12-03 08:43:53 +0000367 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
368 SSAUpdateVRs.push_back(OrigReg);
369 }
370}
371
Evan Cheng75eb5352009-12-07 10:15:19 +0000372/// ProcessPHI - Process PHI node in TailBB by turning it into a copy in PredBB.
373/// Remember the source register that's contributed by PredBB and update SSA
374/// update map.
Evan Cheng79fc6f42009-12-04 09:42:45 +0000375void TailDuplicatePass::ProcessPHI(MachineInstr *MI,
376 MachineBasicBlock *TailBB,
377 MachineBasicBlock *PredBB,
Evan Cheng75eb5352009-12-07 10:15:19 +0000378 DenseMap<unsigned, unsigned> &LocalVRMap,
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000379 SmallVector<std::pair<unsigned,unsigned>, 4> &Copies,
Rafael Espindola33b46582011-06-10 21:01:53 +0000380 const DenseSet<unsigned> &RegsUsedByPhi,
Rafael Espindola689d7d52011-06-09 23:22:56 +0000381 bool Remove) {
Evan Cheng79fc6f42009-12-04 09:42:45 +0000382 unsigned DefReg = MI->getOperand(0).getReg();
383 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
384 assert(SrcOpIdx && "Unable to find matching PHI source?");
385 unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
Evan Cheng75eb5352009-12-07 10:15:19 +0000386 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000387 LocalVRMap.insert(std::make_pair(DefReg, SrcReg));
Evan Cheng75eb5352009-12-07 10:15:19 +0000388
389 // Insert a copy from source to the end of the block. The def register is the
390 // available value liveout of the block.
391 unsigned NewDef = MRI->createVirtualRegister(RC);
392 Copies.push_back(std::make_pair(NewDef, SrcReg));
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000393 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
Evan Cheng75eb5352009-12-07 10:15:19 +0000394 AddSSAUpdateEntry(DefReg, NewDef, PredBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000395
Rafael Espindola689d7d52011-06-09 23:22:56 +0000396 if (!Remove)
397 return;
398
Evan Cheng79fc6f42009-12-04 09:42:45 +0000399 // Remove PredBB from the PHI node.
400 MI->RemoveOperand(SrcOpIdx+1);
401 MI->RemoveOperand(SrcOpIdx);
402 if (MI->getNumOperands() == 1)
403 MI->eraseFromParent();
404}
405
406/// DuplicateInstruction - Duplicate a TailBB instruction to PredBB and update
407/// the source operands due to earlier PHI translation.
408void TailDuplicatePass::DuplicateInstruction(MachineInstr *MI,
409 MachineBasicBlock *TailBB,
410 MachineBasicBlock *PredBB,
411 MachineFunction &MF,
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000412 DenseMap<unsigned, unsigned> &LocalVRMap,
413 const DenseSet<unsigned> &UsedByPhi) {
Jakob Stoklund Olesen30ac0462010-01-06 23:47:07 +0000414 MachineInstr *NewMI = TII->duplicate(MI, MF);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000415 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
416 MachineOperand &MO = NewMI->getOperand(i);
417 if (!MO.isReg())
418 continue;
419 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000420 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng79fc6f42009-12-04 09:42:45 +0000421 continue;
422 if (MO.isDef()) {
423 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
424 unsigned NewReg = MRI->createVirtualRegister(RC);
425 MO.setReg(NewReg);
426 LocalVRMap.insert(std::make_pair(Reg, NewReg));
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000427 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
Evan Cheng11572ba2009-12-04 19:09:10 +0000428 AddSSAUpdateEntry(Reg, NewReg, PredBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000429 } else {
430 DenseMap<unsigned, unsigned>::iterator VI = LocalVRMap.find(Reg);
431 if (VI != LocalVRMap.end())
432 MO.setReg(VI->second);
433 }
434 }
435 PredBB->insert(PredBB->end(), NewMI);
436}
437
438/// UpdateSuccessorsPHIs - After FromBB is tail duplicated into its predecessor
439/// blocks, the successors have gained new predecessors. Update the PHI
440/// instructions in them accordingly.
Evan Cheng75eb5352009-12-07 10:15:19 +0000441void
442TailDuplicatePass::UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
443 SmallVector<MachineBasicBlock*, 8> &TDBBs,
Evan Cheng79fc6f42009-12-04 09:42:45 +0000444 SmallSetVector<MachineBasicBlock*,8> &Succs) {
445 for (SmallSetVector<MachineBasicBlock*, 8>::iterator SI = Succs.begin(),
446 SE = Succs.end(); SI != SE; ++SI) {
447 MachineBasicBlock *SuccBB = *SI;
448 for (MachineBasicBlock::iterator II = SuccBB->begin(), EE = SuccBB->end();
449 II != EE; ++II) {
Chris Lattner518bb532010-02-09 19:54:29 +0000450 if (!II->isPHI())
Evan Cheng79fc6f42009-12-04 09:42:45 +0000451 break;
Evan Cheng75eb5352009-12-07 10:15:19 +0000452 unsigned Idx = 0;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000453 for (unsigned i = 1, e = II->getNumOperands(); i != e; i += 2) {
Evan Cheng75eb5352009-12-07 10:15:19 +0000454 MachineOperand &MO = II->getOperand(i+1);
455 if (MO.getMBB() == FromBB) {
456 Idx = i;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000457 break;
Evan Cheng75eb5352009-12-07 10:15:19 +0000458 }
459 }
460
461 assert(Idx != 0);
462 MachineOperand &MO0 = II->getOperand(Idx);
463 unsigned Reg = MO0.getReg();
464 if (isDead) {
465 // Folded into the previous BB.
466 // There could be duplicate phi source entries. FIXME: Should sdisel
467 // or earlier pass fixed this?
468 for (unsigned i = II->getNumOperands()-2; i != Idx; i -= 2) {
469 MachineOperand &MO = II->getOperand(i+1);
470 if (MO.getMBB() == FromBB) {
471 II->RemoveOperand(i+1);
472 II->RemoveOperand(i);
473 }
474 }
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000475 } else
476 Idx = 0;
477
478 // If Idx is set, the operands at Idx and Idx+1 must be removed.
479 // We reuse the location to avoid expensive RemoveOperand calls.
480
Evan Cheng75eb5352009-12-07 10:15:19 +0000481 DenseMap<unsigned,AvailableValsTy>::iterator LI=SSAUpdateVals.find(Reg);
482 if (LI != SSAUpdateVals.end()) {
483 // This register is defined in the tail block.
Evan Cheng79fc6f42009-12-04 09:42:45 +0000484 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
Evan Cheng11572ba2009-12-04 19:09:10 +0000485 MachineBasicBlock *SrcBB = LI->second[j].first;
Rafael Espindolad3f4eea2011-06-09 23:55:56 +0000486 // If we didn't duplicate a bb into a particular predecessor, we
487 // might still have added an entry to SSAUpdateVals to correcly
488 // recompute SSA. If that case, avoid adding a dummy extra argument
489 // this PHI.
490 if (!SrcBB->isSuccessor(SuccBB))
491 continue;
492
Evan Cheng11572ba2009-12-04 19:09:10 +0000493 unsigned SrcReg = LI->second[j].second;
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000494 if (Idx != 0) {
495 II->getOperand(Idx).setReg(SrcReg);
496 II->getOperand(Idx+1).setMBB(SrcBB);
497 Idx = 0;
498 } else {
499 II->addOperand(MachineOperand::CreateReg(SrcReg, false));
500 II->addOperand(MachineOperand::CreateMBB(SrcBB));
501 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000502 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000503 } else {
504 // Live in tail block, must also be live in predecessors.
505 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
506 MachineBasicBlock *SrcBB = TDBBs[j];
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000507 if (Idx != 0) {
508 II->getOperand(Idx).setReg(Reg);
509 II->getOperand(Idx+1).setMBB(SrcBB);
510 Idx = 0;
511 } else {
512 II->addOperand(MachineOperand::CreateReg(Reg, false));
513 II->addOperand(MachineOperand::CreateMBB(SrcBB));
514 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000515 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000516 }
Jakob Stoklund Olesen09eeac92010-02-11 00:34:33 +0000517 if (Idx != 0) {
518 II->RemoveOperand(Idx+1);
519 II->RemoveOperand(Idx);
520 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000521 }
522 }
523}
524
Rafael Espindola54c25622011-06-09 19:54:42 +0000525/// shouldTailDuplicate - Determine if it is profitable to duplicate this block.
Evan Cheng75eb5352009-12-07 10:15:19 +0000526bool
Rafael Espindola54c25622011-06-09 19:54:42 +0000527TailDuplicatePass::shouldTailDuplicate(const MachineFunction &MF,
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000528 bool IsSimple,
Rafael Espindola54c25622011-06-09 19:54:42 +0000529 MachineBasicBlock &TailBB) {
530 // Only duplicate blocks that end with unconditional branches.
531 if (TailBB.canFallThrough())
532 return false;
533
Rafael Espindolaec324e52011-06-17 05:54:50 +0000534 // Don't try to tail-duplicate single-block loops.
535 if (TailBB.isSuccessor(&TailBB))
536 return false;
537
Rafael Espindola54c25622011-06-09 19:54:42 +0000538 // Set the limit on the cost to duplicate. When optimizing for size,
Bob Wilson15acadd2009-11-26 00:32:21 +0000539 // duplicate only one, because one branch instruction can be eliminated to
540 // compensate for the duplication.
541 unsigned MaxDuplicateCount;
Jakob Stoklund Olesen83520622011-01-30 20:38:12 +0000542 if (TailDuplicateSize.getNumOccurrences() == 0 &&
543 MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize))
Bob Wilson38582252009-11-30 18:56:45 +0000544 MaxDuplicateCount = 1;
Bob Wilson15acadd2009-11-26 00:32:21 +0000545 else
546 MaxDuplicateCount = TailDuplicateSize;
547
Rafael Espindolaec324e52011-06-17 05:54:50 +0000548 // If the target has hardware branch prediction that can handle indirect
549 // branches, duplicating them can often make them predictable when there
550 // are common paths through the code. The limit needs to be high enough
551 // to allow undoing the effects of tail merging and other optimizations
552 // that rearrange the predecessors of the indirect branch.
Bob Wilsoncb44b282010-01-16 00:42:25 +0000553
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000554 bool HasIndirectbr = false;
555 if (!TailBB.empty())
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000556 HasIndirectbr = TailBB.back().isIndirectBranch();
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000557
558 if (HasIndirectbr && PreRegAlloc)
559 MaxDuplicateCount = 20;
Bob Wilsonbfdcf3b2010-01-15 06:29:17 +0000560
Bob Wilson15acadd2009-11-26 00:32:21 +0000561 // Check the instructions in the block to determine whether tail-duplication
562 // is invalid or unlikely to be profitable.
Bob Wilsonf1e01dc2009-12-02 17:15:24 +0000563 unsigned InstrCount = 0;
Evan Cheng7c2a4a32011-12-06 22:12:01 +0000564 for (MachineBasicBlock::iterator I = TailBB.begin(); I != TailBB.end(); ++I) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000565 // Non-duplicable things shouldn't be tail-duplicated.
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000566 if (I->isNotDuplicable())
Rafael Espindolaec324e52011-06-17 05:54:50 +0000567 return false;
568
Evan Cheng79fc6f42009-12-04 09:42:45 +0000569 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
570 // A return may expand into a lot more instructions (e.g. reload of callee
571 // saved registers) after PEI.
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000572 if (PreRegAlloc && I->isReturn())
Rafael Espindolaec324e52011-06-17 05:54:50 +0000573 return false;
574
575 // Avoid duplicating calls before register allocation. Calls presents a
576 // barrier to register allocation so duplicating them may end up increasing
577 // spills.
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000578 if (PreRegAlloc && I->isCall())
Rafael Espindolaec324e52011-06-17 05:54:50 +0000579 return false;
580
Devang Patelcbe1e312010-03-16 21:02:07 +0000581 if (!I->isPHI() && !I->isDebugValue())
Bob Wilsonf1e01dc2009-12-02 17:15:24 +0000582 InstrCount += 1;
Rafael Espindolaec324e52011-06-17 05:54:50 +0000583
584 if (InstrCount > MaxDuplicateCount)
585 return false;
Bob Wilson15acadd2009-11-26 00:32:21 +0000586 }
Bob Wilson15acadd2009-11-26 00:32:21 +0000587
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000588 if (HasIndirectbr && PreRegAlloc)
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000589 return true;
590
591 if (IsSimple)
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000592 return true;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000593
594 if (!PreRegAlloc)
595 return true;
596
Rafael Espindola40179bf2011-06-24 15:50:56 +0000597 return canCompletelyDuplicateBB(TailBB);
Rafael Espindola54c25622011-06-09 19:54:42 +0000598}
599
Rafael Espindola275c1f92011-06-20 04:16:35 +0000600/// isSimpleBB - True if this BB has only one unconditional jump.
601bool
602TailDuplicatePass::isSimpleBB(MachineBasicBlock *TailBB) {
603 if (TailBB->succ_size() != 1)
604 return false;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000605 if (TailBB->pred_empty())
606 return false;
Rafael Espindolad6379a92011-06-22 22:31:57 +0000607 MachineBasicBlock::iterator I = TailBB->begin();
Rafael Espindola275c1f92011-06-20 04:16:35 +0000608 MachineBasicBlock::iterator E = TailBB->end();
Rafael Espindolad6379a92011-06-22 22:31:57 +0000609 while (I != E && I->isDebugValue())
Rafael Espindola275c1f92011-06-20 04:16:35 +0000610 ++I;
611 if (I == E)
612 return true;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000613 return I->isUnconditionalBranch();
Rafael Espindola275c1f92011-06-20 04:16:35 +0000614}
615
616static bool
617bothUsedInPHI(const MachineBasicBlock &A,
618 SmallPtrSet<MachineBasicBlock*, 8> SuccsB) {
619 for (MachineBasicBlock::const_succ_iterator SI = A.succ_begin(),
620 SE = A.succ_end(); SI != SE; ++SI) {
621 MachineBasicBlock *BB = *SI;
622 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
623 return true;
624 }
625
626 return false;
627}
628
629bool
Rafael Espindola40179bf2011-06-24 15:50:56 +0000630TailDuplicatePass::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
Rafael Espindola275c1f92011-06-20 04:16:35 +0000631 SmallPtrSet<MachineBasicBlock*, 8> Succs(BB.succ_begin(), BB.succ_end());
632
633 for (MachineBasicBlock::pred_iterator PI = BB.pred_begin(),
634 PE = BB.pred_end(); PI != PE; ++PI) {
635 MachineBasicBlock *PredBB = *PI;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000636
Rafael Espindola40179bf2011-06-24 15:50:56 +0000637 if (PredBB->succ_size() > 1)
638 return false;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000639
Rafael Espindola275c1f92011-06-20 04:16:35 +0000640 MachineBasicBlock *PredTBB = NULL, *PredFBB = NULL;
641 SmallVector<MachineOperand, 4> PredCond;
642 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
643 return false;
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000644
Rafael Espindola40179bf2011-06-24 15:50:56 +0000645 if (!PredCond.empty())
Rafael Espindola9dbbd872011-06-23 03:41:29 +0000646 return false;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000647 }
648 return true;
649}
650
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000651bool
Rafael Espindola275c1f92011-06-20 04:16:35 +0000652TailDuplicatePass::duplicateSimpleBB(MachineBasicBlock *TailBB,
653 SmallVector<MachineBasicBlock*, 8> &TDBBs,
654 const DenseSet<unsigned> &UsedByPhi,
655 SmallVector<MachineInstr*, 16> &Copies) {
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000656 SmallPtrSet<MachineBasicBlock*, 8> Succs(TailBB->succ_begin(),
657 TailBB->succ_end());
Rafael Espindola275c1f92011-06-20 04:16:35 +0000658 SmallVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
659 TailBB->pred_end());
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000660 bool Changed = false;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000661 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
662 PE = Preds.end(); PI != PE; ++PI) {
663 MachineBasicBlock *PredBB = *PI;
664
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000665 if (PredBB->getLandingPadSuccessor())
666 continue;
667
668 if (bothUsedInPHI(*PredBB, Succs))
669 continue;
670
Rafael Espindola275c1f92011-06-20 04:16:35 +0000671 MachineBasicBlock *PredTBB = NULL, *PredFBB = NULL;
672 SmallVector<MachineOperand, 4> PredCond;
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000673 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
674 continue;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000675
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000676 Changed = true;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000677 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
678 << "From simple Succ: " << *TailBB);
679
680 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
Francois Pichet289a2792011-06-20 05:19:37 +0000681 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(PredBB));
Rafael Espindola275c1f92011-06-20 04:16:35 +0000682
Rafael Espindola275c1f92011-06-20 04:16:35 +0000683 // Make PredFBB explicit.
684 if (PredCond.empty())
685 PredFBB = PredTBB;
686
687 // Make fall through explicit.
688 if (!PredTBB)
689 PredTBB = NextBB;
690 if (!PredFBB)
691 PredFBB = NextBB;
692
693 // Redirect
694 if (PredFBB == TailBB)
695 PredFBB = NewTarget;
696 if (PredTBB == TailBB)
697 PredTBB = NewTarget;
698
699 // Make the branch unconditional if possible
Rafael Espindola689c2472011-06-20 14:11:42 +0000700 if (PredTBB == PredFBB) {
701 PredCond.clear();
Rafael Espindola275c1f92011-06-20 04:16:35 +0000702 PredFBB = NULL;
Rafael Espindola689c2472011-06-20 14:11:42 +0000703 }
Rafael Espindola275c1f92011-06-20 04:16:35 +0000704
705 // Avoid adding fall through branches.
706 if (PredFBB == NextBB)
707 PredFBB = NULL;
708 if (PredTBB == NextBB && PredFBB == NULL)
709 PredTBB = NULL;
710
711 TII->RemoveBranch(*PredBB);
712
713 if (PredTBB)
714 TII->InsertBranch(*PredBB, PredTBB, PredFBB, PredCond, DebugLoc());
715
716 PredBB->removeSuccessor(TailBB);
Rafael Espindola689c2472011-06-20 14:11:42 +0000717 unsigned NumSuccessors = PredBB->succ_size();
718 assert(NumSuccessors <= 1);
719 if (NumSuccessors == 0 || *PredBB->succ_begin() != NewTarget)
720 PredBB->addSuccessor(NewTarget);
Rafael Espindola275c1f92011-06-20 04:16:35 +0000721
722 TDBBs.push_back(PredBB);
Rafael Espindola275c1f92011-06-20 04:16:35 +0000723 }
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000724 return Changed;
Rafael Espindola275c1f92011-06-20 04:16:35 +0000725}
726
Rafael Espindola54c25622011-06-09 19:54:42 +0000727/// TailDuplicate - If it is profitable, duplicate TailBB's contents in each
728/// of its predecessors.
729bool
Rafael Espindola6a9d2b12011-07-04 01:21:42 +0000730TailDuplicatePass::TailDuplicate(MachineBasicBlock *TailBB,
731 bool IsSimple,
732 MachineFunction &MF,
Rafael Espindola54c25622011-06-09 19:54:42 +0000733 SmallVector<MachineBasicBlock*, 8> &TDBBs,
734 SmallVector<MachineInstr*, 16> &Copies) {
David Greene00dec1b2010-01-05 01:25:15 +0000735 DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
Evan Cheng75eb5352009-12-07 10:15:19 +0000736
Rafael Espindola275c1f92011-06-20 04:16:35 +0000737 DenseSet<unsigned> UsedByPhi;
738 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
739
Rafael Espindolad7f35fa2011-06-24 15:47:41 +0000740 if (IsSimple)
741 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
Rafael Espindola275c1f92011-06-20 04:16:35 +0000742
Bob Wilson15acadd2009-11-26 00:32:21 +0000743 // Iterate through all the unique predecessors and tail-duplicate this
744 // block into them, if possible. Copying the list ahead of time also
745 // avoids trouble with the predecessor list reallocating.
746 bool Changed = false;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000747 SmallSetVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
748 TailBB->pred_end());
Bob Wilson15acadd2009-11-26 00:32:21 +0000749 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
750 PE = Preds.end(); PI != PE; ++PI) {
751 MachineBasicBlock *PredBB = *PI;
752
753 assert(TailBB != PredBB &&
754 "Single-block loop should have been rejected earlier!");
Rafael Espindola9a9a3a52011-06-10 20:08:23 +0000755 // EH edges are ignored by AnalyzeBranch.
756 if (PredBB->succ_size() > 1)
757 continue;
Bob Wilson15acadd2009-11-26 00:32:21 +0000758
759 MachineBasicBlock *PredTBB, *PredFBB;
760 SmallVector<MachineOperand, 4> PredCond;
761 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
762 continue;
763 if (!PredCond.empty())
764 continue;
Bob Wilson15acadd2009-11-26 00:32:21 +0000765 // Don't duplicate into a fall-through predecessor (at least for now).
766 if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
767 continue;
768
David Greene00dec1b2010-01-05 01:25:15 +0000769 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
Bob Wilson15acadd2009-11-26 00:32:21 +0000770 << "From Succ: " << *TailBB);
771
Evan Cheng75eb5352009-12-07 10:15:19 +0000772 TDBBs.push_back(PredBB);
773
Bob Wilson15acadd2009-11-26 00:32:21 +0000774 // Remove PredBB's unconditional branch.
775 TII->RemoveBranch(*PredBB);
Evan Cheng111e7622009-12-03 08:43:53 +0000776
Bob Wilson15acadd2009-11-26 00:32:21 +0000777 // Clone the contents of TailBB into PredBB.
Evan Cheng111e7622009-12-03 08:43:53 +0000778 DenseMap<unsigned, unsigned> LocalVRMap;
Evan Cheng3466f132009-12-15 01:44:10 +0000779 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
Evan Cheng111e7622009-12-03 08:43:53 +0000780 MachineBasicBlock::iterator I = TailBB->begin();
Evan Cheng79fc6f42009-12-04 09:42:45 +0000781 while (I != TailBB->end()) {
782 MachineInstr *MI = &*I;
783 ++I;
Chris Lattner518bb532010-02-09 19:54:29 +0000784 if (MI->isPHI()) {
Evan Cheng111e7622009-12-03 08:43:53 +0000785 // Replace the uses of the def of the PHI with the register coming
786 // from PredBB.
Rafael Espindola689d7d52011-06-09 23:22:56 +0000787 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000788 } else {
789 // Replace def of virtual registers with new registers, and update
790 // uses with PHI source register or the new registers.
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000791 DuplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap, UsedByPhi);
Evan Cheng111e7622009-12-03 08:43:53 +0000792 }
Bob Wilson15acadd2009-11-26 00:32:21 +0000793 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000794 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
Evan Cheng3466f132009-12-15 01:44:10 +0000795 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +0000796 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
797 TII->get(TargetOpcode::COPY),
798 CopyInfos[i].first).addReg(CopyInfos[i].second));
Evan Cheng75eb5352009-12-07 10:15:19 +0000799 }
Rafael Espindolaec324e52011-06-17 05:54:50 +0000800
801 // Simplify
802 TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true);
803
Bob Wilson15acadd2009-11-26 00:32:21 +0000804 NumInstrDups += TailBB->size() - 1; // subtract one for removed branch
805
806 // Update the CFG.
807 PredBB->removeSuccessor(PredBB->succ_begin());
808 assert(PredBB->succ_empty() &&
809 "TailDuplicate called on block with multiple successors!");
810 for (MachineBasicBlock::succ_iterator I = TailBB->succ_begin(),
Evan Cheng79fc6f42009-12-04 09:42:45 +0000811 E = TailBB->succ_end(); I != E; ++I)
812 PredBB->addSuccessor(*I);
Bob Wilson15acadd2009-11-26 00:32:21 +0000813
814 Changed = true;
815 ++NumTailDups;
816 }
817
818 // If TailBB was duplicated into all its predecessors except for the prior
819 // block, which falls through unconditionally, move the contents of this
820 // block into the prior block.
Evan Cheng79fc6f42009-12-04 09:42:45 +0000821 MachineBasicBlock *PrevBB = prior(MachineFunction::iterator(TailBB));
Bob Wilson15acadd2009-11-26 00:32:21 +0000822 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
823 SmallVector<MachineOperand, 4> PriorCond;
Bob Wilson15acadd2009-11-26 00:32:21 +0000824 // This has to check PrevBB->succ_size() because EH edges are ignored by
825 // AnalyzeBranch.
Rafael Espindolaa899b222011-06-09 21:43:25 +0000826 if (PrevBB->succ_size() == 1 &&
827 !TII->AnalyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) &&
828 PriorCond.empty() && !PriorTBB && TailBB->pred_size() == 1 &&
Bob Wilson15acadd2009-11-26 00:32:21 +0000829 !TailBB->hasAddressTaken()) {
David Greene00dec1b2010-01-05 01:25:15 +0000830 DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
Bob Wilson15acadd2009-11-26 00:32:21 +0000831 << "From MBB: " << *TailBB);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000832 if (PreRegAlloc) {
833 DenseMap<unsigned, unsigned> LocalVRMap;
Evan Cheng3466f132009-12-15 01:44:10 +0000834 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
Evan Cheng79fc6f42009-12-04 09:42:45 +0000835 MachineBasicBlock::iterator I = TailBB->begin();
836 // Process PHI instructions first.
Chris Lattner518bb532010-02-09 19:54:29 +0000837 while (I != TailBB->end() && I->isPHI()) {
Evan Cheng79fc6f42009-12-04 09:42:45 +0000838 // Replace the uses of the def of the PHI with the register coming
839 // from PredBB.
840 MachineInstr *MI = &*I++;
Rafael Espindola689d7d52011-06-09 23:22:56 +0000841 ProcessPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000842 if (MI->getParent())
843 MI->eraseFromParent();
844 }
845
846 // Now copy the non-PHI instructions.
847 while (I != TailBB->end()) {
848 // Replace def of virtual registers with new registers, and update
849 // uses with PHI source register or the new registers.
850 MachineInstr *MI = &*I++;
Rafael Espindola0f28c3f2011-06-09 22:53:47 +0000851 DuplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap, UsedByPhi);
Evan Cheng79fc6f42009-12-04 09:42:45 +0000852 MI->eraseFromParent();
853 }
Evan Cheng75eb5352009-12-07 10:15:19 +0000854 MachineBasicBlock::iterator Loc = PrevBB->getFirstTerminator();
Evan Cheng3466f132009-12-15 01:44:10 +0000855 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +0000856 Copies.push_back(BuildMI(*PrevBB, Loc, DebugLoc(),
857 TII->get(TargetOpcode::COPY),
858 CopyInfos[i].first)
859 .addReg(CopyInfos[i].second));
Evan Cheng75eb5352009-12-07 10:15:19 +0000860 }
Evan Cheng79fc6f42009-12-04 09:42:45 +0000861 } else {
862 // No PHIs to worry about, just splice the instructions over.
863 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
864 }
865 PrevBB->removeSuccessor(PrevBB->succ_begin());
866 assert(PrevBB->succ_empty());
867 PrevBB->transferSuccessors(TailBB);
Evan Cheng75eb5352009-12-07 10:15:19 +0000868 TDBBs.push_back(PrevBB);
Bob Wilson15acadd2009-11-26 00:32:21 +0000869 Changed = true;
870 }
871
Rafael Espindola689d7d52011-06-09 23:22:56 +0000872 // If this is after register allocation, there are no phis to fix.
873 if (!PreRegAlloc)
874 return Changed;
875
876 // If we made no changes so far, we are safe.
877 if (!Changed)
878 return Changed;
879
880
881 // Handle the nasty case in that we duplicated a block that is part of a loop
882 // into some but not all of its predecessors. For example:
Rafael Espindola4d7b4572011-06-09 23:51:45 +0000883 // 1 -> 2 <-> 3 |
884 // \ |
885 // \---> rest |
Rafael Espindola689d7d52011-06-09 23:22:56 +0000886 // if we duplicate 2 into 1 but not into 3, we end up with
Rafael Espindola4d7b4572011-06-09 23:51:45 +0000887 // 12 -> 3 <-> 2 -> rest |
888 // \ / |
889 // \----->-----/ |
Rafael Espindola689d7d52011-06-09 23:22:56 +0000890 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
891 // with a phi in 3 (which now dominates 2).
892 // What we do here is introduce a copy in 3 of the register defined by the
893 // phi, just like when we are duplicating 2 into 3, but we don't copy any
894 // real instructions or remove the 3 -> 2 edge from the phi in 2.
895 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
896 PE = Preds.end(); PI != PE; ++PI) {
897 MachineBasicBlock *PredBB = *PI;
898 if (std::find(TDBBs.begin(), TDBBs.end(), PredBB) != TDBBs.end())
899 continue;
900
901 // EH edges
902 if (PredBB->succ_size() != 1)
903 continue;
904
905 DenseMap<unsigned, unsigned> LocalVRMap;
906 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
907 MachineBasicBlock::iterator I = TailBB->begin();
908 // Process PHI instructions first.
909 while (I != TailBB->end() && I->isPHI()) {
910 // Replace the uses of the def of the PHI with the register coming
911 // from PredBB.
912 MachineInstr *MI = &*I++;
913 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
914 }
915 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
916 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
917 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
918 TII->get(TargetOpcode::COPY),
919 CopyInfos[i].first).addReg(CopyInfos[i].second));
920 }
921 }
922
Bob Wilson15acadd2009-11-26 00:32:21 +0000923 return Changed;
924}
925
926/// RemoveDeadBlock - Remove the specified dead machine basic block from the
927/// function, updating the CFG.
Bob Wilson2d521e52009-11-26 21:38:41 +0000928void TailDuplicatePass::RemoveDeadBlock(MachineBasicBlock *MBB) {
Bob Wilson15acadd2009-11-26 00:32:21 +0000929 assert(MBB->pred_empty() && "MBB must be dead!");
David Greene00dec1b2010-01-05 01:25:15 +0000930 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
Bob Wilson15acadd2009-11-26 00:32:21 +0000931
932 // Remove all successors.
933 while (!MBB->succ_empty())
934 MBB->removeSuccessor(MBB->succ_end()-1);
935
Bob Wilson15acadd2009-11-26 00:32:21 +0000936 // Remove the block.
937 MBB->eraseFromParent();
938}