blob: 170a8e19ed40450ff8201bbad6db1035b50739ab [file] [log] [blame]
Bob Wilson2d4ff122009-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"
Bob Wilson2d4ff122009-11-26 00:32:21 +000016#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/DenseSet.h"
18#include "llvm/ADT/OwningPtr.h"
19#include "llvm/ADT/SetVector.h"
20#include "llvm/ADT/SmallSet.h"
21#include "llvm/ADT/Statistic.h"
Akira Hatanakaa07ffb52014-02-12 18:09:18 +000022#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Bob Wilson2d4ff122009-11-26 00:32:21 +000023#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesen0c76d6e2010-07-10 22:42:59 +000024#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/CodeGen/MachineModuleInfo.h"
Evan Cheng1bbe6be2009-12-03 08:43:53 +000026#include "llvm/CodeGen/MachineRegisterInfo.h"
27#include "llvm/CodeGen/MachineSSAUpdater.h"
Evan Chengbc2453d2012-05-30 00:42:39 +000028#include "llvm/CodeGen/RegisterScavenging.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Function.h"
Bob Wilson2d4ff122009-11-26 00:32:21 +000030#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/Debug.h"
Evan Chengcc770622009-12-07 10:15:19 +000032#include "llvm/Support/ErrorHandling.h"
Bob Wilson2d4ff122009-11-26 00:32:21 +000033#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Target/TargetInstrInfo.h"
35#include "llvm/Target/TargetRegisterInfo.h"
Bob Wilson2d4ff122009-11-26 00:32:21 +000036using namespace llvm;
37
Evan Chengcc770622009-12-07 10:15:19 +000038STATISTIC(NumTails , "Number of tails duplicated");
Bob Wilson2d4ff122009-11-26 00:32:21 +000039STATISTIC(NumTailDups , "Number of tail duplicated blocks");
40STATISTIC(NumInstrDups , "Additional instructions due to tail duplication");
41STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
Rafael Espindoladfbf6de2011-06-08 14:13:31 +000042STATISTIC(NumAddedPHIs , "Number of phis added");
Bob Wilson2d4ff122009-11-26 00:32:21 +000043
44// Heuristic for tail duplication.
45static cl::opt<unsigned>
46TailDuplicateSize("tail-dup-size",
47 cl::desc("Maximum instructions to consider tail duplicating"),
48 cl::init(2), cl::Hidden);
49
Evan Chengcc770622009-12-07 10:15:19 +000050static cl::opt<bool>
51TailDupVerify("tail-dup-verify",
52 cl::desc("Verify sanity of PHI instructions during taildup"),
53 cl::init(false), cl::Hidden);
54
55static cl::opt<unsigned>
56TailDupLimit("tail-dup-limit", cl::init(~0U), cl::Hidden);
57
Evan Cheng9e672552009-12-04 19:09:10 +000058typedef std::vector<std::pair<MachineBasicBlock*,unsigned> > AvailableValsTy;
Evan Cheng1bbe6be2009-12-03 08:43:53 +000059
Bob Wilson2d4ff122009-11-26 00:32:21 +000060namespace {
Bob Wilson9594db52009-11-26 21:38:41 +000061 /// TailDuplicatePass - Perform tail duplication.
62 class TailDuplicatePass : public MachineFunctionPass {
Bob Wilson2d4ff122009-11-26 00:32:21 +000063 const TargetInstrInfo *TII;
Evan Chengbc2453d2012-05-30 00:42:39 +000064 const TargetRegisterInfo *TRI;
Akira Hatanakaa07ffb52014-02-12 18:09:18 +000065 const MachineBranchProbabilityInfo *MBPI;
Bob Wilson2d4ff122009-11-26 00:32:21 +000066 MachineModuleInfo *MMI;
Evan Cheng1bbe6be2009-12-03 08:43:53 +000067 MachineRegisterInfo *MRI;
Benjamin Kramer3de5d402012-06-06 13:53:41 +000068 OwningPtr<RegScavenger> RS;
Andrew Trickc0449172012-02-08 21:22:30 +000069 bool PreRegAlloc;
Evan Cheng1bbe6be2009-12-03 08:43:53 +000070
71 // SSAUpdateVRs - A list of virtual registers for which to update SSA form.
72 SmallVector<unsigned, 16> SSAUpdateVRs;
73
74 // SSAUpdateVals - For each virtual register in SSAUpdateVals keep a list of
75 // source virtual registers.
76 DenseMap<unsigned, AvailableValsTy> SSAUpdateVals;
Bob Wilson2d4ff122009-11-26 00:32:21 +000077
78 public:
79 static char ID;
Andrew Trickc0449172012-02-08 21:22:30 +000080 explicit TailDuplicatePass() :
81 MachineFunctionPass(ID), PreRegAlloc(false) {}
Bob Wilson2d4ff122009-11-26 00:32:21 +000082
83 virtual bool runOnMachineFunction(MachineFunction &MF);
Bob Wilson2d4ff122009-11-26 00:32:21 +000084
Akira Hatanakaa07ffb52014-02-12 18:09:18 +000085 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
86
Bob Wilson2d4ff122009-11-26 00:32:21 +000087 private:
Evan Cheng9e672552009-12-04 19:09:10 +000088 void AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
89 MachineBasicBlock *BB);
Evan Cheng6154dbd2009-12-04 09:42:45 +000090 void ProcessPHI(MachineInstr *MI, MachineBasicBlock *TailBB,
91 MachineBasicBlock *PredBB,
Evan Chengcc770622009-12-07 10:15:19 +000092 DenseMap<unsigned, unsigned> &LocalVRMap,
Craig Topperb94011f2013-07-14 04:42:23 +000093 SmallVectorImpl<std::pair<unsigned,unsigned> > &Copies,
Rafael Espindolac735f132011-06-09 23:22:56 +000094 const DenseSet<unsigned> &UsedByPhi,
95 bool Remove);
Evan Cheng6154dbd2009-12-04 09:42:45 +000096 void DuplicateInstruction(MachineInstr *MI,
97 MachineBasicBlock *TailBB,
98 MachineBasicBlock *PredBB,
99 MachineFunction &MF,
Rafael Espindola81512fc2011-06-09 22:53:47 +0000100 DenseMap<unsigned, unsigned> &LocalVRMap,
101 const DenseSet<unsigned> &UsedByPhi);
Evan Chengcc770622009-12-07 10:15:19 +0000102 void UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
Craig Topperb94011f2013-07-14 04:42:23 +0000103 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
Evan Chengcc770622009-12-07 10:15:19 +0000104 SmallSetVector<MachineBasicBlock*, 8> &Succs);
Bob Wilson2d4ff122009-11-26 00:32:21 +0000105 bool TailDuplicateBlocks(MachineFunction &MF);
Rafael Espindola73f93932011-06-09 19:54:42 +0000106 bool shouldTailDuplicate(const MachineFunction &MF,
Rafael Espindolae25a8712011-06-23 03:41:29 +0000107 bool IsSimple, MachineBasicBlock &TailBB);
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000108 bool isSimpleBB(MachineBasicBlock *TailBB);
Rafael Espindola5135ae22011-06-24 15:50:56 +0000109 bool canCompletelyDuplicateBB(MachineBasicBlock &BB);
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000110 bool duplicateSimpleBB(MachineBasicBlock *TailBB,
Craig Topperb94011f2013-07-14 04:42:23 +0000111 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000112 const DenseSet<unsigned> &RegsUsedByPhi,
Craig Topperb94011f2013-07-14 04:42:23 +0000113 SmallVectorImpl<MachineInstr *> &Copies);
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000114 bool TailDuplicate(MachineBasicBlock *TailBB,
115 bool IsSimple,
116 MachineFunction &MF,
Craig Topperb94011f2013-07-14 04:42:23 +0000117 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
118 SmallVectorImpl<MachineInstr *> &Copies);
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000119 bool TailDuplicateAndUpdate(MachineBasicBlock *MBB,
120 bool IsSimple,
121 MachineFunction &MF);
122
Bob Wilson2d4ff122009-11-26 00:32:21 +0000123 void RemoveDeadBlock(MachineBasicBlock *MBB);
124 };
125
Bob Wilson9594db52009-11-26 21:38:41 +0000126 char TailDuplicatePass::ID = 0;
Bob Wilson2d4ff122009-11-26 00:32:21 +0000127}
128
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000129char &llvm::TailDuplicateID = TailDuplicatePass::ID;
130
131INITIALIZE_PASS(TailDuplicatePass, "tailduplication", "Tail Duplication",
132 false, false)
Bob Wilson2d4ff122009-11-26 00:32:21 +0000133
Bob Wilson9594db52009-11-26 21:38:41 +0000134bool TailDuplicatePass::runOnMachineFunction(MachineFunction &MF) {
Bob Wilson2d4ff122009-11-26 00:32:21 +0000135 TII = MF.getTarget().getInstrInfo();
Evan Chengbc2453d2012-05-30 00:42:39 +0000136 TRI = MF.getTarget().getRegisterInfo();
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000137 MRI = &MF.getRegInfo();
Bob Wilson2d4ff122009-11-26 00:32:21 +0000138 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
Akira Hatanakaa07ffb52014-02-12 18:09:18 +0000139 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
140
Andrew Trickc0449172012-02-08 21:22:30 +0000141 PreRegAlloc = MRI->isSSA();
Benjamin Kramer3de5d402012-06-06 13:53:41 +0000142 RS.reset();
Evan Chengbc2453d2012-05-30 00:42:39 +0000143 if (MRI->tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF))
Benjamin Kramer3de5d402012-06-06 13:53:41 +0000144 RS.reset(new RegScavenger());
Bob Wilson2d4ff122009-11-26 00:32:21 +0000145
146 bool MadeChange = false;
Jakob Stoklund Olesen73ef9552010-01-15 19:59:57 +0000147 while (TailDuplicateBlocks(MF))
148 MadeChange = true;
Bob Wilson2d4ff122009-11-26 00:32:21 +0000149
150 return MadeChange;
151}
152
Akira Hatanakaa07ffb52014-02-12 18:09:18 +0000153void TailDuplicatePass::getAnalysisUsage(AnalysisUsage &AU) const {
154 AU.addRequired<MachineBranchProbabilityInfo>();
155 MachineFunctionPass::getAnalysisUsage(AU);
156}
157
Evan Chengcc770622009-12-07 10:15:19 +0000158static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
159 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
160 MachineBasicBlock *MBB = I;
161 SmallSetVector<MachineBasicBlock*, 8> Preds(MBB->pred_begin(),
162 MBB->pred_end());
163 MachineBasicBlock::iterator MI = MBB->begin();
164 while (MI != MBB->end()) {
Chris Lattnerb06015a2010-02-09 19:54:29 +0000165 if (!MI->isPHI())
Evan Chengcc770622009-12-07 10:15:19 +0000166 break;
167 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
168 PE = Preds.end(); PI != PE; ++PI) {
169 MachineBasicBlock *PredBB = *PI;
170 bool Found = false;
171 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
172 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
173 if (PHIBB == PredBB) {
174 Found = true;
175 break;
176 }
177 }
178 if (!Found) {
David Greene85afc852010-01-05 01:25:15 +0000179 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
180 dbgs() << " missing input from predecessor BB#"
Evan Chengcc770622009-12-07 10:15:19 +0000181 << PredBB->getNumber() << '\n';
182 llvm_unreachable(0);
183 }
184 }
185
186 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
187 MachineBasicBlock *PHIBB = MI->getOperand(i+1).getMBB();
188 if (CheckExtra && !Preds.count(PHIBB)) {
David Greene85afc852010-01-05 01:25:15 +0000189 dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber()
Evan Chengcc770622009-12-07 10:15:19 +0000190 << ": " << *MI;
David Greene85afc852010-01-05 01:25:15 +0000191 dbgs() << " extra input from predecessor BB#"
Evan Chengcc770622009-12-07 10:15:19 +0000192 << PHIBB->getNumber() << '\n';
Rafael Espindola9e97a892011-06-09 23:55:56 +0000193 llvm_unreachable(0);
Evan Chengcc770622009-12-07 10:15:19 +0000194 }
195 if (PHIBB->getNumber() < 0) {
David Greene85afc852010-01-05 01:25:15 +0000196 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
197 dbgs() << " non-existing BB#" << PHIBB->getNumber() << '\n';
Evan Chengcc770622009-12-07 10:15:19 +0000198 llvm_unreachable(0);
199 }
200 }
201 ++MI;
202 }
203 }
204}
205
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000206/// TailDuplicateAndUpdate - Tail duplicate the block and cleanup.
207bool
208TailDuplicatePass::TailDuplicateAndUpdate(MachineBasicBlock *MBB,
209 bool IsSimple,
210 MachineFunction &MF) {
211 // Save the successors list.
212 SmallSetVector<MachineBasicBlock*, 8> Succs(MBB->succ_begin(),
213 MBB->succ_end());
214
215 SmallVector<MachineBasicBlock*, 8> TDBBs;
216 SmallVector<MachineInstr*, 16> Copies;
217 if (!TailDuplicate(MBB, IsSimple, MF, TDBBs, Copies))
218 return false;
219
220 ++NumTails;
221
222 SmallVector<MachineInstr*, 8> NewPHIs;
223 MachineSSAUpdater SSAUpdate(MF, &NewPHIs);
224
225 // TailBB's immediate successors are now successors of those predecessors
226 // which duplicated TailBB. Add the predecessors as sources to the PHI
227 // instructions.
228 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
229 if (PreRegAlloc)
230 UpdateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
231
232 // If it is dead, remove it.
233 if (isDead) {
234 NumInstrDups -= MBB->size();
235 RemoveDeadBlock(MBB);
236 ++NumDeadBlocks;
237 }
238
239 // Update SSA form.
240 if (!SSAUpdateVRs.empty()) {
241 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
242 unsigned VReg = SSAUpdateVRs[i];
243 SSAUpdate.Initialize(VReg);
244
245 // If the original definition is still around, add it as an available
246 // value.
247 MachineInstr *DefMI = MRI->getVRegDef(VReg);
248 MachineBasicBlock *DefBB = 0;
249 if (DefMI) {
250 DefBB = DefMI->getParent();
251 SSAUpdate.AddAvailableValue(DefBB, VReg);
252 }
253
254 // Add the new vregs as available values.
255 DenseMap<unsigned, AvailableValsTy>::iterator LI =
256 SSAUpdateVals.find(VReg);
257 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
258 MachineBasicBlock *SrcBB = LI->second[j].first;
259 unsigned SrcReg = LI->second[j].second;
260 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
261 }
262
263 // Rewrite uses that are outside of the original def's block.
264 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
265 while (UI != MRI->use_end()) {
266 MachineOperand &UseMO = UI.getOperand();
267 MachineInstr *UseMI = &*UI;
268 ++UI;
269 if (UseMI->isDebugValue()) {
270 // SSAUpdate can replace the use with an undef. That creates
271 // a debug instruction that is a kill.
272 // FIXME: Should it SSAUpdate job to delete debug instructions
273 // instead of replacing the use with undef?
274 UseMI->eraseFromParent();
275 continue;
276 }
277 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
278 continue;
279 SSAUpdate.RewriteUse(UseMO);
280 }
281 }
282
283 SSAUpdateVRs.clear();
284 SSAUpdateVals.clear();
285 }
286
287 // Eliminate some of the copies inserted by tail duplication to maintain
288 // SSA form.
289 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
290 MachineInstr *Copy = Copies[i];
291 if (!Copy->isCopy())
292 continue;
293 unsigned Dst = Copy->getOperand(0).getReg();
294 unsigned Src = Copy->getOperand(1).getReg();
Jakob Stoklund Olesen00f07de2012-05-20 18:42:51 +0000295 if (MRI->hasOneNonDBGUse(Src) &&
296 MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000297 // Copy is the only use. Do trivial copy propagation here.
298 MRI->replaceRegWith(Dst, Src);
299 Copy->eraseFromParent();
300 }
301 }
302
303 if (NewPHIs.size())
304 NumAddedPHIs += NewPHIs.size();
305
306 return true;
307}
308
Bob Wilson2d4ff122009-11-26 00:32:21 +0000309/// TailDuplicateBlocks - Look for small blocks that are unconditionally
310/// branched to and do not fall through. Tail-duplicate their instructions
311/// into their predecessors to eliminate (dynamic) branches.
Bob Wilson9594db52009-11-26 21:38:41 +0000312bool TailDuplicatePass::TailDuplicateBlocks(MachineFunction &MF) {
Bob Wilson2d4ff122009-11-26 00:32:21 +0000313 bool MadeChange = false;
314
Evan Chengcc770622009-12-07 10:15:19 +0000315 if (PreRegAlloc && TailDupVerify) {
David Greene85afc852010-01-05 01:25:15 +0000316 DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
Evan Chengcc770622009-12-07 10:15:19 +0000317 VerifyPHIs(MF, true);
318 }
319
Bob Wilson2d4ff122009-11-26 00:32:21 +0000320 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
321 MachineBasicBlock *MBB = I++;
322
Evan Chengcc770622009-12-07 10:15:19 +0000323 if (NumTails == TailDupLimit)
324 break;
325
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000326 bool IsSimple = isSimpleBB(MBB);
Bob Wilson2d4ff122009-11-26 00:32:21 +0000327
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000328 if (!shouldTailDuplicate(MF, IsSimple, *MBB))
Rafael Espindola79dc4e72011-07-04 00:13:36 +0000329 continue;
Evan Chengcc770622009-12-07 10:15:19 +0000330
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000331 MadeChange |= TailDuplicateAndUpdate(MBB, IsSimple, MF);
Bob Wilson2d4ff122009-11-26 00:32:21 +0000332 }
Rafael Espindola79dc4e72011-07-04 00:13:36 +0000333
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000334 if (PreRegAlloc && TailDupVerify)
335 VerifyPHIs(MF, false);
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000336
Bob Wilson2d4ff122009-11-26 00:32:21 +0000337 return MadeChange;
338}
339
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000340static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
341 const MachineRegisterInfo *MRI) {
342 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
343 UE = MRI->use_end(); UI != UE; ++UI) {
344 MachineInstr *UseMI = &*UI;
Rafael Espindolae0304d12011-06-17 13:59:43 +0000345 if (UseMI->isDebugValue())
346 continue;
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000347 if (UseMI->getParent() != BB)
348 return true;
349 }
350 return false;
351}
352
353static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
354 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
355 if (MI->getOperand(i+1).getMBB() == SrcBB)
356 return i;
357 return 0;
358}
359
Rafael Espindola81512fc2011-06-09 22:53:47 +0000360
361// Remember which registers are used by phis in this block. This is
362// used to determine which registers are liveout while modifying the
363// block (which is why we need to copy the information).
364static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
Rafael Espindola0f62e4c2011-06-10 21:01:53 +0000365 DenseSet<unsigned> *UsedByPhi) {
Rafael Espindola81512fc2011-06-09 22:53:47 +0000366 for(MachineBasicBlock::const_iterator I = BB.begin(), E = BB.end();
367 I != E; ++I) {
368 const MachineInstr &MI = *I;
369 if (!MI.isPHI())
370 break;
371 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
372 unsigned SrcReg = MI.getOperand(i).getReg();
373 UsedByPhi->insert(SrcReg);
374 }
375 }
376}
377
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000378/// AddSSAUpdateEntry - Add a definition and source virtual registers pair for
379/// SSA update.
Evan Cheng9e672552009-12-04 19:09:10 +0000380void TailDuplicatePass::AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
381 MachineBasicBlock *BB) {
382 DenseMap<unsigned, AvailableValsTy>::iterator LI= SSAUpdateVals.find(OrigReg);
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000383 if (LI != SSAUpdateVals.end())
Evan Cheng9e672552009-12-04 19:09:10 +0000384 LI->second.push_back(std::make_pair(BB, NewReg));
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000385 else {
386 AvailableValsTy Vals;
Evan Cheng9e672552009-12-04 19:09:10 +0000387 Vals.push_back(std::make_pair(BB, NewReg));
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000388 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
389 SSAUpdateVRs.push_back(OrigReg);
390 }
391}
392
Evan Chengcc770622009-12-07 10:15:19 +0000393/// ProcessPHI - Process PHI node in TailBB by turning it into a copy in PredBB.
394/// Remember the source register that's contributed by PredBB and update SSA
395/// update map.
Tobias Grosser84f34be2013-07-14 06:12:01 +0000396void TailDuplicatePass::ProcessPHI(
397 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
398 DenseMap<unsigned, unsigned> &LocalVRMap,
399 SmallVectorImpl<std::pair<unsigned, unsigned> > &Copies,
400 const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) {
Evan Cheng6154dbd2009-12-04 09:42:45 +0000401 unsigned DefReg = MI->getOperand(0).getReg();
402 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
403 assert(SrcOpIdx && "Unable to find matching PHI source?");
404 unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
Evan Chengcc770622009-12-07 10:15:19 +0000405 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000406 LocalVRMap.insert(std::make_pair(DefReg, SrcReg));
Evan Chengcc770622009-12-07 10:15:19 +0000407
408 // Insert a copy from source to the end of the block. The def register is the
409 // available value liveout of the block.
410 unsigned NewDef = MRI->createVirtualRegister(RC);
411 Copies.push_back(std::make_pair(NewDef, SrcReg));
Rafael Espindola81512fc2011-06-09 22:53:47 +0000412 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
Evan Chengcc770622009-12-07 10:15:19 +0000413 AddSSAUpdateEntry(DefReg, NewDef, PredBB);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000414
Rafael Espindolac735f132011-06-09 23:22:56 +0000415 if (!Remove)
416 return;
417
Evan Cheng6154dbd2009-12-04 09:42:45 +0000418 // Remove PredBB from the PHI node.
419 MI->RemoveOperand(SrcOpIdx+1);
420 MI->RemoveOperand(SrcOpIdx);
421 if (MI->getNumOperands() == 1)
422 MI->eraseFromParent();
423}
424
425/// DuplicateInstruction - Duplicate a TailBB instruction to PredBB and update
426/// the source operands due to earlier PHI translation.
427void TailDuplicatePass::DuplicateInstruction(MachineInstr *MI,
428 MachineBasicBlock *TailBB,
429 MachineBasicBlock *PredBB,
430 MachineFunction &MF,
Rafael Espindola81512fc2011-06-09 22:53:47 +0000431 DenseMap<unsigned, unsigned> &LocalVRMap,
432 const DenseSet<unsigned> &UsedByPhi) {
Jakob Stoklund Olesen29a64c92010-01-06 23:47:07 +0000433 MachineInstr *NewMI = TII->duplicate(MI, MF);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000434 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
435 MachineOperand &MO = NewMI->getOperand(i);
436 if (!MO.isReg())
437 continue;
438 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +0000439 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng6154dbd2009-12-04 09:42:45 +0000440 continue;
441 if (MO.isDef()) {
442 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
443 unsigned NewReg = MRI->createVirtualRegister(RC);
444 MO.setReg(NewReg);
445 LocalVRMap.insert(std::make_pair(Reg, NewReg));
Rafael Espindola81512fc2011-06-09 22:53:47 +0000446 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
Evan Cheng9e672552009-12-04 19:09:10 +0000447 AddSSAUpdateEntry(Reg, NewReg, PredBB);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000448 } else {
449 DenseMap<unsigned, unsigned>::iterator VI = LocalVRMap.find(Reg);
Jakob Stoklund Olesen00f07de2012-05-20 18:42:51 +0000450 if (VI != LocalVRMap.end()) {
Evan Cheng6154dbd2009-12-04 09:42:45 +0000451 MO.setReg(VI->second);
Jakob Stoklund Olesen00f07de2012-05-20 18:42:51 +0000452 MRI->constrainRegClass(VI->second, MRI->getRegClass(Reg));
453 }
Evan Cheng6154dbd2009-12-04 09:42:45 +0000454 }
455 }
Evan Chengd0c02962012-02-20 07:51:58 +0000456 PredBB->insert(PredBB->instr_end(), NewMI);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000457}
458
459/// UpdateSuccessorsPHIs - After FromBB is tail duplicated into its predecessor
460/// blocks, the successors have gained new predecessors. Update the PHI
461/// instructions in them accordingly.
Evan Chengcc770622009-12-07 10:15:19 +0000462void
463TailDuplicatePass::UpdateSuccessorsPHIs(MachineBasicBlock *FromBB, bool isDead,
Craig Topperb94011f2013-07-14 04:42:23 +0000464 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
Evan Cheng6154dbd2009-12-04 09:42:45 +0000465 SmallSetVector<MachineBasicBlock*,8> &Succs) {
466 for (SmallSetVector<MachineBasicBlock*, 8>::iterator SI = Succs.begin(),
467 SE = Succs.end(); SI != SE; ++SI) {
468 MachineBasicBlock *SuccBB = *SI;
469 for (MachineBasicBlock::iterator II = SuccBB->begin(), EE = SuccBB->end();
470 II != EE; ++II) {
Chris Lattnerb06015a2010-02-09 19:54:29 +0000471 if (!II->isPHI())
Evan Cheng6154dbd2009-12-04 09:42:45 +0000472 break;
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +0000473 MachineInstrBuilder MIB(*FromBB->getParent(), II);
Evan Chengcc770622009-12-07 10:15:19 +0000474 unsigned Idx = 0;
Evan Cheng6154dbd2009-12-04 09:42:45 +0000475 for (unsigned i = 1, e = II->getNumOperands(); i != e; i += 2) {
Evan Chengcc770622009-12-07 10:15:19 +0000476 MachineOperand &MO = II->getOperand(i+1);
477 if (MO.getMBB() == FromBB) {
478 Idx = i;
Evan Cheng6154dbd2009-12-04 09:42:45 +0000479 break;
Evan Chengcc770622009-12-07 10:15:19 +0000480 }
481 }
482
483 assert(Idx != 0);
484 MachineOperand &MO0 = II->getOperand(Idx);
485 unsigned Reg = MO0.getReg();
486 if (isDead) {
487 // Folded into the previous BB.
488 // There could be duplicate phi source entries. FIXME: Should sdisel
489 // or earlier pass fixed this?
490 for (unsigned i = II->getNumOperands()-2; i != Idx; i -= 2) {
491 MachineOperand &MO = II->getOperand(i+1);
492 if (MO.getMBB() == FromBB) {
493 II->RemoveOperand(i+1);
494 II->RemoveOperand(i);
495 }
496 }
Jakob Stoklund Olesen75521ca2010-02-11 00:34:33 +0000497 } else
498 Idx = 0;
499
500 // If Idx is set, the operands at Idx and Idx+1 must be removed.
501 // We reuse the location to avoid expensive RemoveOperand calls.
502
Evan Chengcc770622009-12-07 10:15:19 +0000503 DenseMap<unsigned,AvailableValsTy>::iterator LI=SSAUpdateVals.find(Reg);
504 if (LI != SSAUpdateVals.end()) {
505 // This register is defined in the tail block.
Evan Cheng6154dbd2009-12-04 09:42:45 +0000506 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
Evan Cheng9e672552009-12-04 19:09:10 +0000507 MachineBasicBlock *SrcBB = LI->second[j].first;
Rafael Espindola9e97a892011-06-09 23:55:56 +0000508 // If we didn't duplicate a bb into a particular predecessor, we
509 // might still have added an entry to SSAUpdateVals to correcly
510 // recompute SSA. If that case, avoid adding a dummy extra argument
511 // this PHI.
512 if (!SrcBB->isSuccessor(SuccBB))
513 continue;
514
Evan Cheng9e672552009-12-04 19:09:10 +0000515 unsigned SrcReg = LI->second[j].second;
Jakob Stoklund Olesen75521ca2010-02-11 00:34:33 +0000516 if (Idx != 0) {
517 II->getOperand(Idx).setReg(SrcReg);
518 II->getOperand(Idx+1).setMBB(SrcBB);
519 Idx = 0;
520 } else {
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +0000521 MIB.addReg(SrcReg).addMBB(SrcBB);
Jakob Stoklund Olesen75521ca2010-02-11 00:34:33 +0000522 }
Evan Cheng6154dbd2009-12-04 09:42:45 +0000523 }
Evan Chengcc770622009-12-07 10:15:19 +0000524 } else {
525 // Live in tail block, must also be live in predecessors.
526 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
527 MachineBasicBlock *SrcBB = TDBBs[j];
Jakob Stoklund Olesen75521ca2010-02-11 00:34:33 +0000528 if (Idx != 0) {
529 II->getOperand(Idx).setReg(Reg);
530 II->getOperand(Idx+1).setMBB(SrcBB);
531 Idx = 0;
532 } else {
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +0000533 MIB.addReg(Reg).addMBB(SrcBB);
Jakob Stoklund Olesen75521ca2010-02-11 00:34:33 +0000534 }
Evan Chengcc770622009-12-07 10:15:19 +0000535 }
Evan Cheng6154dbd2009-12-04 09:42:45 +0000536 }
Jakob Stoklund Olesen75521ca2010-02-11 00:34:33 +0000537 if (Idx != 0) {
538 II->RemoveOperand(Idx+1);
539 II->RemoveOperand(Idx);
540 }
Evan Cheng6154dbd2009-12-04 09:42:45 +0000541 }
542 }
543}
544
Rafael Espindola73f93932011-06-09 19:54:42 +0000545/// shouldTailDuplicate - Determine if it is profitable to duplicate this block.
Evan Chengcc770622009-12-07 10:15:19 +0000546bool
Rafael Espindola73f93932011-06-09 19:54:42 +0000547TailDuplicatePass::shouldTailDuplicate(const MachineFunction &MF,
Rafael Espindolae25a8712011-06-23 03:41:29 +0000548 bool IsSimple,
Rafael Espindola73f93932011-06-09 19:54:42 +0000549 MachineBasicBlock &TailBB) {
550 // Only duplicate blocks that end with unconditional branches.
551 if (TailBB.canFallThrough())
552 return false;
553
Rafael Espindola79a4b7e2011-06-17 05:54:50 +0000554 // Don't try to tail-duplicate single-block loops.
555 if (TailBB.isSuccessor(&TailBB))
556 return false;
557
Rafael Espindola73f93932011-06-09 19:54:42 +0000558 // Set the limit on the cost to duplicate. When optimizing for size,
Bob Wilson2d4ff122009-11-26 00:32:21 +0000559 // duplicate only one, because one branch instruction can be eliminated to
560 // compensate for the duplication.
561 unsigned MaxDuplicateCount;
Jakob Stoklund Olesen9af7afc2011-01-30 20:38:12 +0000562 if (TailDuplicateSize.getNumOccurrences() == 0 &&
Bill Wendling698e84f2012-12-30 10:32:01 +0000563 MF.getFunction()->getAttributes().
564 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize))
Bob Wilson598f8ff2009-11-30 18:56:45 +0000565 MaxDuplicateCount = 1;
Bob Wilson2d4ff122009-11-26 00:32:21 +0000566 else
567 MaxDuplicateCount = TailDuplicateSize;
568
Rafael Espindola79a4b7e2011-06-17 05:54:50 +0000569 // If the target has hardware branch prediction that can handle indirect
570 // branches, duplicating them can often make them predictable when there
571 // are common paths through the code. The limit needs to be high enough
572 // to allow undoing the effects of tail merging and other optimizations
573 // that rearrange the predecessors of the indirect branch.
Bob Wilson97598f02010-01-16 00:42:25 +0000574
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000575 bool HasIndirectbr = false;
576 if (!TailBB.empty())
Evan Cheng7f8e5632011-12-07 07:15:52 +0000577 HasIndirectbr = TailBB.back().isIndirectBranch();
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000578
579 if (HasIndirectbr && PreRegAlloc)
580 MaxDuplicateCount = 20;
Bob Wilson1a234c02010-01-15 06:29:17 +0000581
Bob Wilson2d4ff122009-11-26 00:32:21 +0000582 // Check the instructions in the block to determine whether tail-duplication
583 // is invalid or unlikely to be profitable.
Bob Wilsonfffbc0c2009-12-02 17:15:24 +0000584 unsigned InstrCount = 0;
Evan Cheng2a81dd42011-12-06 22:12:01 +0000585 for (MachineBasicBlock::iterator I = TailBB.begin(); I != TailBB.end(); ++I) {
Bob Wilson2d4ff122009-11-26 00:32:21 +0000586 // Non-duplicable things shouldn't be tail-duplicated.
Evan Cheng7f8e5632011-12-07 07:15:52 +0000587 if (I->isNotDuplicable())
Rafael Espindola79a4b7e2011-06-17 05:54:50 +0000588 return false;
589
Evan Cheng6154dbd2009-12-04 09:42:45 +0000590 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
591 // A return may expand into a lot more instructions (e.g. reload of callee
592 // saved registers) after PEI.
Evan Cheng7f8e5632011-12-07 07:15:52 +0000593 if (PreRegAlloc && I->isReturn())
Rafael Espindola79a4b7e2011-06-17 05:54:50 +0000594 return false;
595
596 // Avoid duplicating calls before register allocation. Calls presents a
597 // barrier to register allocation so duplicating them may end up increasing
598 // spills.
Evan Cheng7f8e5632011-12-07 07:15:52 +0000599 if (PreRegAlloc && I->isCall())
Rafael Espindola79a4b7e2011-06-17 05:54:50 +0000600 return false;
601
Devang Patela0bb7152010-03-16 21:02:07 +0000602 if (!I->isPHI() && !I->isDebugValue())
Bob Wilsonfffbc0c2009-12-02 17:15:24 +0000603 InstrCount += 1;
Rafael Espindola79a4b7e2011-06-17 05:54:50 +0000604
605 if (InstrCount > MaxDuplicateCount)
606 return false;
Bob Wilson2d4ff122009-11-26 00:32:21 +0000607 }
Bob Wilson2d4ff122009-11-26 00:32:21 +0000608
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000609 if (HasIndirectbr && PreRegAlloc)
Rafael Espindolae25a8712011-06-23 03:41:29 +0000610 return true;
611
612 if (IsSimple)
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000613 return true;
Rafael Espindolae25a8712011-06-23 03:41:29 +0000614
615 if (!PreRegAlloc)
616 return true;
617
Rafael Espindola5135ae22011-06-24 15:50:56 +0000618 return canCompletelyDuplicateBB(TailBB);
Rafael Espindola73f93932011-06-09 19:54:42 +0000619}
620
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000621/// isSimpleBB - True if this BB has only one unconditional jump.
622bool
623TailDuplicatePass::isSimpleBB(MachineBasicBlock *TailBB) {
624 if (TailBB->succ_size() != 1)
625 return false;
Rafael Espindolae25a8712011-06-23 03:41:29 +0000626 if (TailBB->pred_empty())
627 return false;
Rafael Espindola2496c1f2011-06-22 22:31:57 +0000628 MachineBasicBlock::iterator I = TailBB->begin();
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000629 MachineBasicBlock::iterator E = TailBB->end();
Rafael Espindola2496c1f2011-06-22 22:31:57 +0000630 while (I != E && I->isDebugValue())
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000631 ++I;
632 if (I == E)
633 return true;
Evan Cheng7f8e5632011-12-07 07:15:52 +0000634 return I->isUnconditionalBranch();
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000635}
636
637static bool
638bothUsedInPHI(const MachineBasicBlock &A,
639 SmallPtrSet<MachineBasicBlock*, 8> SuccsB) {
640 for (MachineBasicBlock::const_succ_iterator SI = A.succ_begin(),
641 SE = A.succ_end(); SI != SE; ++SI) {
642 MachineBasicBlock *BB = *SI;
643 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
644 return true;
645 }
646
647 return false;
648}
649
650bool
Rafael Espindola5135ae22011-06-24 15:50:56 +0000651TailDuplicatePass::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000652 for (MachineBasicBlock::pred_iterator PI = BB.pred_begin(),
653 PE = BB.pred_end(); PI != PE; ++PI) {
654 MachineBasicBlock *PredBB = *PI;
Rafael Espindolae25a8712011-06-23 03:41:29 +0000655
Rafael Espindola5135ae22011-06-24 15:50:56 +0000656 if (PredBB->succ_size() > 1)
657 return false;
Rafael Espindolae25a8712011-06-23 03:41:29 +0000658
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000659 MachineBasicBlock *PredTBB = NULL, *PredFBB = NULL;
660 SmallVector<MachineOperand, 4> PredCond;
661 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
662 return false;
Rafael Espindolae25a8712011-06-23 03:41:29 +0000663
Rafael Espindola5135ae22011-06-24 15:50:56 +0000664 if (!PredCond.empty())
Rafael Espindolae25a8712011-06-23 03:41:29 +0000665 return false;
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000666 }
667 return true;
668}
669
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000670bool
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000671TailDuplicatePass::duplicateSimpleBB(MachineBasicBlock *TailBB,
Craig Topperb94011f2013-07-14 04:42:23 +0000672 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
673 const DenseSet<unsigned> &UsedByPhi,
674 SmallVectorImpl<MachineInstr *> &Copies) {
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000675 SmallPtrSet<MachineBasicBlock*, 8> Succs(TailBB->succ_begin(),
676 TailBB->succ_end());
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000677 SmallVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
678 TailBB->pred_end());
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000679 bool Changed = false;
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000680 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
681 PE = Preds.end(); PI != PE; ++PI) {
682 MachineBasicBlock *PredBB = *PI;
683
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000684 if (PredBB->getLandingPadSuccessor())
685 continue;
686
687 if (bothUsedInPHI(*PredBB, Succs))
688 continue;
689
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000690 MachineBasicBlock *PredTBB = NULL, *PredFBB = NULL;
691 SmallVector<MachineOperand, 4> PredCond;
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000692 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
693 continue;
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000694
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000695 Changed = true;
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000696 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
697 << "From simple Succ: " << *TailBB);
698
699 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
Francois Pichet3f60aca2011-06-20 05:19:37 +0000700 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(PredBB));
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000701
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000702 // Make PredFBB explicit.
703 if (PredCond.empty())
704 PredFBB = PredTBB;
705
706 // Make fall through explicit.
707 if (!PredTBB)
708 PredTBB = NextBB;
709 if (!PredFBB)
710 PredFBB = NextBB;
711
712 // Redirect
713 if (PredFBB == TailBB)
714 PredFBB = NewTarget;
715 if (PredTBB == TailBB)
716 PredTBB = NewTarget;
717
718 // Make the branch unconditional if possible
Rafael Espindola336e1022011-06-20 14:11:42 +0000719 if (PredTBB == PredFBB) {
720 PredCond.clear();
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000721 PredFBB = NULL;
Rafael Espindola336e1022011-06-20 14:11:42 +0000722 }
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000723
724 // Avoid adding fall through branches.
725 if (PredFBB == NextBB)
726 PredFBB = NULL;
727 if (PredTBB == NextBB && PredFBB == NULL)
728 PredTBB = NULL;
729
730 TII->RemoveBranch(*PredBB);
731
732 if (PredTBB)
733 TII->InsertBranch(*PredBB, PredTBB, PredFBB, PredCond, DebugLoc());
734
Akira Hatanakaa07ffb52014-02-12 18:09:18 +0000735 uint32_t Weight = MBPI->getEdgeWeight(PredBB, TailBB);
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000736 PredBB->removeSuccessor(TailBB);
Rafael Espindola336e1022011-06-20 14:11:42 +0000737 unsigned NumSuccessors = PredBB->succ_size();
738 assert(NumSuccessors <= 1);
739 if (NumSuccessors == 0 || *PredBB->succ_begin() != NewTarget)
Akira Hatanakaa07ffb52014-02-12 18:09:18 +0000740 PredBB->addSuccessor(NewTarget, Weight);
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000741
742 TDBBs.push_back(PredBB);
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000743 }
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000744 return Changed;
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000745}
746
Rafael Espindola73f93932011-06-09 19:54:42 +0000747/// TailDuplicate - If it is profitable, duplicate TailBB's contents in each
748/// of its predecessors.
749bool
Rafael Espindolaf9f012e2011-07-04 01:21:42 +0000750TailDuplicatePass::TailDuplicate(MachineBasicBlock *TailBB,
751 bool IsSimple,
752 MachineFunction &MF,
Craig Topperb94011f2013-07-14 04:42:23 +0000753 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
754 SmallVectorImpl<MachineInstr *> &Copies) {
David Greene85afc852010-01-05 01:25:15 +0000755 DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
Evan Chengcc770622009-12-07 10:15:19 +0000756
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000757 DenseSet<unsigned> UsedByPhi;
758 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
759
Rafael Espindolacb0213b2011-06-24 15:47:41 +0000760 if (IsSimple)
761 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
Rafael Espindolaef636bf2011-06-20 04:16:35 +0000762
Bob Wilson2d4ff122009-11-26 00:32:21 +0000763 // Iterate through all the unique predecessors and tail-duplicate this
764 // block into them, if possible. Copying the list ahead of time also
765 // avoids trouble with the predecessor list reallocating.
766 bool Changed = false;
Evan Cheng6154dbd2009-12-04 09:42:45 +0000767 SmallSetVector<MachineBasicBlock*, 8> Preds(TailBB->pred_begin(),
768 TailBB->pred_end());
Bob Wilson2d4ff122009-11-26 00:32:21 +0000769 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
770 PE = Preds.end(); PI != PE; ++PI) {
771 MachineBasicBlock *PredBB = *PI;
772
773 assert(TailBB != PredBB &&
774 "Single-block loop should have been rejected earlier!");
Rafael Espindola1ffadd72011-06-10 20:08:23 +0000775 // EH edges are ignored by AnalyzeBranch.
776 if (PredBB->succ_size() > 1)
777 continue;
Bob Wilson2d4ff122009-11-26 00:32:21 +0000778
779 MachineBasicBlock *PredTBB, *PredFBB;
780 SmallVector<MachineOperand, 4> PredCond;
781 if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
782 continue;
783 if (!PredCond.empty())
784 continue;
Bob Wilson2d4ff122009-11-26 00:32:21 +0000785 // Don't duplicate into a fall-through predecessor (at least for now).
786 if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
787 continue;
788
David Greene85afc852010-01-05 01:25:15 +0000789 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
Bob Wilson2d4ff122009-11-26 00:32:21 +0000790 << "From Succ: " << *TailBB);
791
Evan Chengcc770622009-12-07 10:15:19 +0000792 TDBBs.push_back(PredBB);
793
Bob Wilson2d4ff122009-11-26 00:32:21 +0000794 // Remove PredBB's unconditional branch.
795 TII->RemoveBranch(*PredBB);
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000796
Evan Chengbc2453d2012-05-30 00:42:39 +0000797 if (RS && !TailBB->livein_empty()) {
798 // Update PredBB livein.
799 RS->enterBasicBlock(PredBB);
800 if (!PredBB->empty())
801 RS->forward(prior(PredBB->end()));
802 BitVector RegsLiveAtExit(TRI->getNumRegs());
803 RS->getRegsUsed(RegsLiveAtExit, false);
804 for (MachineBasicBlock::livein_iterator I = TailBB->livein_begin(),
805 E = TailBB->livein_end(); I != E; ++I) {
806 if (!RegsLiveAtExit[*I])
807 // If a register is previously livein to the tail but it's not live
808 // at the end of predecessor BB, then it should be added to its
809 // livein list.
810 PredBB->addLiveIn(*I);
811 }
812 }
813
Bob Wilson2d4ff122009-11-26 00:32:21 +0000814 // Clone the contents of TailBB into PredBB.
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000815 DenseMap<unsigned, unsigned> LocalVRMap;
Evan Cheng45430bb2009-12-15 01:44:10 +0000816 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
Evan Chengd0c02962012-02-20 07:51:58 +0000817 // Use instr_iterator here to properly handle bundles, e.g.
818 // ARM Thumb2 IT block.
819 MachineBasicBlock::instr_iterator I = TailBB->instr_begin();
820 while (I != TailBB->instr_end()) {
Evan Cheng6154dbd2009-12-04 09:42:45 +0000821 MachineInstr *MI = &*I;
822 ++I;
Chris Lattnerb06015a2010-02-09 19:54:29 +0000823 if (MI->isPHI()) {
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000824 // Replace the uses of the def of the PHI with the register coming
825 // from PredBB.
Rafael Espindolac735f132011-06-09 23:22:56 +0000826 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000827 } else {
828 // Replace def of virtual registers with new registers, and update
829 // uses with PHI source register or the new registers.
Rafael Espindola81512fc2011-06-09 22:53:47 +0000830 DuplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap, UsedByPhi);
Evan Cheng1bbe6be2009-12-03 08:43:53 +0000831 }
Bob Wilson2d4ff122009-11-26 00:32:21 +0000832 }
Evan Chengcc770622009-12-07 10:15:19 +0000833 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
Evan Cheng45430bb2009-12-15 01:44:10 +0000834 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
Jakob Stoklund Olesen0c76d6e2010-07-10 22:42:59 +0000835 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
836 TII->get(TargetOpcode::COPY),
837 CopyInfos[i].first).addReg(CopyInfos[i].second));
Evan Chengcc770622009-12-07 10:15:19 +0000838 }
Rafael Espindola79a4b7e2011-06-17 05:54:50 +0000839
840 // Simplify
841 TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true);
842
Bob Wilson2d4ff122009-11-26 00:32:21 +0000843 NumInstrDups += TailBB->size() - 1; // subtract one for removed branch
844
845 // Update the CFG.
846 PredBB->removeSuccessor(PredBB->succ_begin());
847 assert(PredBB->succ_empty() &&
848 "TailDuplicate called on block with multiple successors!");
849 for (MachineBasicBlock::succ_iterator I = TailBB->succ_begin(),
Evan Cheng6154dbd2009-12-04 09:42:45 +0000850 E = TailBB->succ_end(); I != E; ++I)
Akira Hatanakaa07ffb52014-02-12 18:09:18 +0000851 PredBB->addSuccessor(*I, MBPI->getEdgeWeight(TailBB, I));
Bob Wilson2d4ff122009-11-26 00:32:21 +0000852
853 Changed = true;
854 ++NumTailDups;
855 }
856
857 // If TailBB was duplicated into all its predecessors except for the prior
858 // block, which falls through unconditionally, move the contents of this
859 // block into the prior block.
Evan Cheng6154dbd2009-12-04 09:42:45 +0000860 MachineBasicBlock *PrevBB = prior(MachineFunction::iterator(TailBB));
Bob Wilson2d4ff122009-11-26 00:32:21 +0000861 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
862 SmallVector<MachineOperand, 4> PriorCond;
Bob Wilson2d4ff122009-11-26 00:32:21 +0000863 // This has to check PrevBB->succ_size() because EH edges are ignored by
864 // AnalyzeBranch.
Andrew Trickc0449172012-02-08 21:22:30 +0000865 if (PrevBB->succ_size() == 1 &&
Rafael Espindolac90a32a2011-06-09 21:43:25 +0000866 !TII->AnalyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) &&
867 PriorCond.empty() && !PriorTBB && TailBB->pred_size() == 1 &&
Bob Wilson2d4ff122009-11-26 00:32:21 +0000868 !TailBB->hasAddressTaken()) {
David Greene85afc852010-01-05 01:25:15 +0000869 DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
Bob Wilson2d4ff122009-11-26 00:32:21 +0000870 << "From MBB: " << *TailBB);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000871 if (PreRegAlloc) {
872 DenseMap<unsigned, unsigned> LocalVRMap;
Evan Cheng45430bb2009-12-15 01:44:10 +0000873 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
Evan Cheng6154dbd2009-12-04 09:42:45 +0000874 MachineBasicBlock::iterator I = TailBB->begin();
875 // Process PHI instructions first.
Chris Lattnerb06015a2010-02-09 19:54:29 +0000876 while (I != TailBB->end() && I->isPHI()) {
Evan Cheng6154dbd2009-12-04 09:42:45 +0000877 // Replace the uses of the def of the PHI with the register coming
878 // from PredBB.
879 MachineInstr *MI = &*I++;
Rafael Espindolac735f132011-06-09 23:22:56 +0000880 ProcessPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000881 if (MI->getParent())
882 MI->eraseFromParent();
883 }
884
885 // Now copy the non-PHI instructions.
886 while (I != TailBB->end()) {
887 // Replace def of virtual registers with new registers, and update
888 // uses with PHI source register or the new registers.
889 MachineInstr *MI = &*I++;
Evan Chengd0c02962012-02-20 07:51:58 +0000890 assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
Rafael Espindola81512fc2011-06-09 22:53:47 +0000891 DuplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap, UsedByPhi);
Evan Cheng6154dbd2009-12-04 09:42:45 +0000892 MI->eraseFromParent();
893 }
Evan Chengcc770622009-12-07 10:15:19 +0000894 MachineBasicBlock::iterator Loc = PrevBB->getFirstTerminator();
Evan Cheng45430bb2009-12-15 01:44:10 +0000895 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
Jakob Stoklund Olesen0c76d6e2010-07-10 22:42:59 +0000896 Copies.push_back(BuildMI(*PrevBB, Loc, DebugLoc(),
897 TII->get(TargetOpcode::COPY),
898 CopyInfos[i].first)
899 .addReg(CopyInfos[i].second));
Evan Chengcc770622009-12-07 10:15:19 +0000900 }
Evan Cheng6154dbd2009-12-04 09:42:45 +0000901 } else {
902 // No PHIs to worry about, just splice the instructions over.
903 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
904 }
905 PrevBB->removeSuccessor(PrevBB->succ_begin());
906 assert(PrevBB->succ_empty());
907 PrevBB->transferSuccessors(TailBB);
Evan Chengcc770622009-12-07 10:15:19 +0000908 TDBBs.push_back(PrevBB);
Bob Wilson2d4ff122009-11-26 00:32:21 +0000909 Changed = true;
910 }
911
Rafael Espindolac735f132011-06-09 23:22:56 +0000912 // If this is after register allocation, there are no phis to fix.
913 if (!PreRegAlloc)
914 return Changed;
915
916 // If we made no changes so far, we are safe.
917 if (!Changed)
918 return Changed;
919
920
921 // Handle the nasty case in that we duplicated a block that is part of a loop
922 // into some but not all of its predecessors. For example:
Rafael Espindolac9e93a42011-06-09 23:51:45 +0000923 // 1 -> 2 <-> 3 |
924 // \ |
925 // \---> rest |
Rafael Espindolac735f132011-06-09 23:22:56 +0000926 // if we duplicate 2 into 1 but not into 3, we end up with
Rafael Espindolac9e93a42011-06-09 23:51:45 +0000927 // 12 -> 3 <-> 2 -> rest |
928 // \ / |
929 // \----->-----/ |
Rafael Espindolac735f132011-06-09 23:22:56 +0000930 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
931 // with a phi in 3 (which now dominates 2).
932 // What we do here is introduce a copy in 3 of the register defined by the
933 // phi, just like when we are duplicating 2 into 3, but we don't copy any
934 // real instructions or remove the 3 -> 2 edge from the phi in 2.
935 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
936 PE = Preds.end(); PI != PE; ++PI) {
937 MachineBasicBlock *PredBB = *PI;
938 if (std::find(TDBBs.begin(), TDBBs.end(), PredBB) != TDBBs.end())
939 continue;
940
941 // EH edges
942 if (PredBB->succ_size() != 1)
943 continue;
944
945 DenseMap<unsigned, unsigned> LocalVRMap;
946 SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
947 MachineBasicBlock::iterator I = TailBB->begin();
948 // Process PHI instructions first.
949 while (I != TailBB->end() && I->isPHI()) {
950 // Replace the uses of the def of the PHI with the register coming
951 // from PredBB.
952 MachineInstr *MI = &*I++;
953 ProcessPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
954 }
955 MachineBasicBlock::iterator Loc = PredBB->getFirstTerminator();
956 for (unsigned i = 0, e = CopyInfos.size(); i != e; ++i) {
957 Copies.push_back(BuildMI(*PredBB, Loc, DebugLoc(),
958 TII->get(TargetOpcode::COPY),
959 CopyInfos[i].first).addReg(CopyInfos[i].second));
960 }
961 }
962
Bob Wilson2d4ff122009-11-26 00:32:21 +0000963 return Changed;
964}
965
966/// RemoveDeadBlock - Remove the specified dead machine basic block from the
967/// function, updating the CFG.
Bob Wilson9594db52009-11-26 21:38:41 +0000968void TailDuplicatePass::RemoveDeadBlock(MachineBasicBlock *MBB) {
Bob Wilson2d4ff122009-11-26 00:32:21 +0000969 assert(MBB->pred_empty() && "MBB must be dead!");
David Greene85afc852010-01-05 01:25:15 +0000970 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
Bob Wilson2d4ff122009-11-26 00:32:21 +0000971
972 // Remove all successors.
973 while (!MBB->succ_empty())
974 MBB->removeSuccessor(MBB->succ_end()-1);
975
Bob Wilson2d4ff122009-11-26 00:32:21 +0000976 // Remove the block.
977 MBB->eraseFromParent();
978}