blob: f78ce91d6ee0bfea0c6b09dc388d558763470c13 [file] [log] [blame]
Chris Lattnera5434ca2003-06-22 20:10:28 +00001//===- TailDuplication.cpp - Simplify CFG through tail duplication --------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnera5434ca2003-06-22 20:10:28 +00009//
10// This pass performs a limited form of tail duplication, intended to simplify
11// CFGs by removing some unconditional branches. This pass is necessary to
12// straighten out loops created by the C front-end, but also is capable of
13// making other code nicer. After this pass is run, the CFG simplify pass
14// should be run to clean up the mess.
15//
16// This pass could be enhanced in the future to use profile information to be
17// more aggressive.
18//
19//===----------------------------------------------------------------------===//
20
21#include "llvm/Transforms/Scalar.h"
Chris Lattner1c884e12003-08-31 21:17:44 +000022#include "llvm/Constant.h"
Chris Lattnera5434ca2003-06-22 20:10:28 +000023#include "llvm/Function.h"
Misha Brukman2b3387a2004-07-29 17:05:13 +000024#include "llvm/Instructions.h"
Chris Lattner540e5f92004-11-22 17:23:57 +000025#include "llvm/IntrinsicInst.h"
Chris Lattnera5434ca2003-06-22 20:10:28 +000026#include "llvm/Pass.h"
27#include "llvm/Type.h"
28#include "llvm/Support/CFG.h"
29#include "llvm/Transforms/Utils/Local.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000030#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/Debug.h"
32#include "llvm/ADT/Statistic.h"
Chris Lattner49525f82004-01-09 06:02:20 +000033using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000034
Chris Lattnera5434ca2003-06-22 20:10:28 +000035namespace {
Chris Lattnerc14da962004-04-18 00:52:43 +000036 cl::opt<unsigned>
37 Threshold("taildup-threshold", cl::desc("Max block size to tail duplicate"),
38 cl::init(6), cl::Hidden);
Chris Lattnera5434ca2003-06-22 20:10:28 +000039 Statistic<> NumEliminated("tailduplicate",
40 "Number of unconditional branches eliminated");
41 Statistic<> NumPHINodes("tailduplicate", "Number of phi nodes inserted");
42
43 class TailDup : public FunctionPass {
44 bool runOnFunction(Function &F);
45 private:
46 inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
47 inline void eliminateUnconditionalBranch(BranchInst *BI);
Chris Lattnera5434ca2003-06-22 20:10:28 +000048 };
49 RegisterOpt<TailDup> X("tailduplicate", "Tail Duplication");
50}
51
Brian Gaeke960707c2003-11-11 22:41:34 +000052// Public interface to the Tail Duplication pass
Chris Lattner3e860842004-09-20 04:43:15 +000053FunctionPass *llvm::createTailDuplicationPass() { return new TailDup(); }
Chris Lattnera5434ca2003-06-22 20:10:28 +000054
55/// runOnFunction - Top level algorithm - Loop over each unconditional branch in
56/// the function, eliminating it if it looks attractive enough.
57///
58bool TailDup::runOnFunction(Function &F) {
59 bool Changed = false;
60 for (Function::iterator I = F.begin(), E = F.end(); I != E; )
Chris Lattner95057f62004-03-16 23:29:09 +000061 if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
Chris Lattnera5434ca2003-06-22 20:10:28 +000062 eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
63 Changed = true;
64 } else {
65 ++I;
66 }
67 return Changed;
68}
69
70/// shouldEliminateUnconditionalBranch - Return true if this branch looks
71/// attractive to eliminate. We eliminate the branch if the destination basic
72/// block has <= 5 instructions in it, not counting PHI nodes. In practice,
73/// since one of these is a terminator instruction, this means that we will add
74/// up to 4 instructions to the new block.
75///
76/// We don't count PHI nodes in the count since they will be removed when the
77/// contents of the block are copied over.
78///
79bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
80 BranchInst *BI = dyn_cast<BranchInst>(TI);
81 if (!BI || !BI->isUnconditional()) return false; // Not an uncond branch!
82
83 BasicBlock *Dest = BI->getSuccessor(0);
84 if (Dest == BI->getParent()) return false; // Do not loop infinitely!
85
Chris Lattnerd78ebd02003-07-23 03:32:41 +000086 // Do not inline a block if we will just get another branch to the same block!
Chris Lattnera64923a2004-03-16 19:45:22 +000087 TerminatorInst *DTI = Dest->getTerminator();
88 if (BranchInst *DBI = dyn_cast<BranchInst>(DTI))
Chris Lattnerd78ebd02003-07-23 03:32:41 +000089 if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
90 return false; // Do not loop infinitely!
91
Chris Lattner95057f62004-03-16 23:29:09 +000092 // FIXME: DemoteRegToStack cannot yet demote invoke instructions to the stack,
93 // because doing so would require breaking critical edges. This should be
94 // fixed eventually.
95 if (!DTI->use_empty())
96 return false;
97
Chris Lattnera5434ca2003-06-22 20:10:28 +000098 // Do not bother working on dead blocks...
99 pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
100 if (PI == PE && Dest != Dest->getParent()->begin())
101 return false; // It's just a dead block, ignore it...
102
103 // Also, do not bother with blocks with only a single predecessor: simplify
104 // CFG will fold these two blocks together!
105 ++PI;
106 if (PI == PE) return false; // Exactly one predecessor!
107
108 BasicBlock::iterator I = Dest->begin();
109 while (isa<PHINode>(*I)) ++I;
110
Chris Lattner540e5f92004-11-22 17:23:57 +0000111 for (unsigned Size = 0; I != Dest->end(); ++I) {
112 if (Size == Threshold) return false; // The block is too large.
113 // Only count instructions that are not debugger intrinsics.
114 if (!isa<DbgInfoIntrinsic>(I)) ++Size;
115 }
Chris Lattnera64923a2004-03-16 19:45:22 +0000116
117 // Do not tail duplicate a block that has thousands of successors into a block
118 // with a single successor if the block has many other predecessors. This can
119 // cause an N^2 explosion in CFG edges (and PHI node entries), as seen in
120 // cases that have a large number of indirect gotos.
Chris Lattner8af74242004-11-01 07:05:07 +0000121 unsigned NumSuccs = DTI->getNumSuccessors();
122 if (NumSuccs > 8) {
123 unsigned TooMany = 128;
124 if (NumSuccs >= TooMany) return false;
125 TooMany = TooMany/NumSuccs;
126 for (; PI != PE; ++PI)
127 if (TooMany-- == 0) return false;
128 }
Chris Lattnera64923a2004-03-16 19:45:22 +0000129
Misha Brukmanb1c93172005-04-21 23:48:37 +0000130 return true;
Chris Lattnera5434ca2003-06-22 20:10:28 +0000131}
132
Chris Lattner2ce32df2004-10-06 03:27:37 +0000133/// FindObviousSharedDomOf - We know there is a branch from SrcBlock to
134/// DestBlock, and that SrcBlock is not the only predecessor of DstBlock. If we
135/// can find a predecessor of SrcBlock that is a dominator of both SrcBlock and
136/// DstBlock, return it.
137static BasicBlock *FindObviousSharedDomOf(BasicBlock *SrcBlock,
138 BasicBlock *DstBlock) {
139 // SrcBlock must have a single predecessor.
140 pred_iterator PI = pred_begin(SrcBlock), PE = pred_end(SrcBlock);
141 if (PI == PE || ++PI != PE) return 0;
142
143 BasicBlock *SrcPred = *pred_begin(SrcBlock);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000144
Chris Lattner2ce32df2004-10-06 03:27:37 +0000145 // Look at the predecessors of DstBlock. One of them will be SrcBlock. If
146 // there is only one other pred, get it, otherwise we can't handle it.
147 PI = pred_begin(DstBlock); PE = pred_end(DstBlock);
148 BasicBlock *DstOtherPred = 0;
149 if (*PI == SrcBlock) {
150 if (++PI == PE) return 0;
151 DstOtherPred = *PI;
152 if (++PI != PE) return 0;
153 } else {
154 DstOtherPred = *PI;
155 if (++PI == PE || *PI != SrcBlock || ++PI != PE) return 0;
156 }
157
158 // We can handle two situations here: "if then" and "if then else" blocks. An
159 // 'if then' situation is just where DstOtherPred == SrcPred.
160 if (DstOtherPred == SrcPred)
161 return SrcPred;
162
163 // Check to see if we have an "if then else" situation, which means that
164 // DstOtherPred will have a single predecessor and it will be SrcPred.
165 PI = pred_begin(DstOtherPred); PE = pred_end(DstOtherPred);
166 if (PI != PE && *PI == SrcPred) {
167 if (++PI != PE) return 0; // Not a single pred.
168 return SrcPred; // Otherwise, it's an "if then" situation. Return the if.
169 }
170
171 // Otherwise, this is something we can't handle.
172 return 0;
173}
174
Chris Lattnera5434ca2003-06-22 20:10:28 +0000175
176/// eliminateUnconditionalBranch - Clone the instructions from the destination
177/// block into the source block, eliminating the specified unconditional branch.
178/// If the destination block defines values used by successors of the dest
179/// block, we may need to insert PHI nodes.
180///
181void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
182 BasicBlock *SourceBlock = Branch->getParent();
183 BasicBlock *DestBlock = Branch->getSuccessor(0);
184 assert(SourceBlock != DestBlock && "Our predicate is broken!");
185
186 DEBUG(std::cerr << "TailDuplication[" << SourceBlock->getParent()->getName()
187 << "]: Eliminating branch: " << *Branch);
188
Chris Lattner2ce32df2004-10-06 03:27:37 +0000189 // See if we can avoid duplicating code by moving it up to a dominator of both
190 // blocks.
191 if (BasicBlock *DomBlock = FindObviousSharedDomOf(SourceBlock, DestBlock)) {
192 DEBUG(std::cerr << "Found shared dominator: " << DomBlock->getName()
193 << "\n");
194
195 // If there are non-phi instructions in DestBlock that have no operands
196 // defined in DestBlock, and if the instruction has no side effects, we can
197 // move the instruction to DomBlock instead of duplicating it.
198 BasicBlock::iterator BBI = DestBlock->begin();
199 while (isa<PHINode>(BBI)) ++BBI;
200 while (!isa<TerminatorInst>(BBI)) {
201 Instruction *I = BBI++;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000202
Chris Lattner2ce32df2004-10-06 03:27:37 +0000203 bool CanHoist = !I->isTrapping() && !I->mayWriteToMemory();
204 if (CanHoist) {
205 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
206 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(op)))
207 if (OpI->getParent() == DestBlock ||
208 (isa<InvokeInst>(OpI) && OpI->getParent() == DomBlock)) {
209 CanHoist = false;
210 break;
211 }
212 if (CanHoist) {
213 // Remove from DestBlock, move right before the term in DomBlock.
214 DestBlock->getInstList().remove(I);
215 DomBlock->getInstList().insert(DomBlock->getTerminator(), I);
216 DEBUG(std::cerr << "Hoisted: " << *I);
217 }
218 }
219 }
220 }
221
Chris Lattner95057f62004-03-16 23:29:09 +0000222 // Tail duplication can not update SSA properties correctly if the values
223 // defined in the duplicated tail are used outside of the tail itself. For
224 // this reason, we spill all values that are used outside of the tail to the
225 // stack.
226 for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
227 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
228 ++UI) {
229 bool ShouldDemote = false;
230 if (cast<Instruction>(*UI)->getParent() != DestBlock) {
231 // We must allow our successors to use tail values in their PHI nodes
232 // (if the incoming value corresponds to the tail block).
233 if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
234 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
235 if (PN->getIncomingValue(i) == I &&
236 PN->getIncomingBlock(i) != DestBlock) {
237 ShouldDemote = true;
238 break;
239 }
240
241 } else {
242 ShouldDemote = true;
243 }
244 } else if (PHINode *PN = dyn_cast<PHINode>(cast<Instruction>(*UI))) {
245 // If the user of this instruction is a PHI node in the current block,
Chris Lattnera3783a52004-03-16 23:36:49 +0000246 // which has an entry from another block using the value, spill it.
247 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
248 if (PN->getIncomingValue(i) == I &&
249 PN->getIncomingBlock(i) != DestBlock) {
250 ShouldDemote = true;
251 break;
252 }
Chris Lattner95057f62004-03-16 23:29:09 +0000253 }
254
255 if (ShouldDemote) {
256 // We found a use outside of the tail. Create a new stack slot to
257 // break this inter-block usage pattern.
258 DemoteRegToStack(*I);
259 break;
260 }
261 }
262
Chris Lattnera5434ca2003-06-22 20:10:28 +0000263 // We are going to have to map operands from the original block B to the new
264 // copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
265 // nodes also define part of this mapping. Loop over these PHI nodes, adding
266 // them to our mapping.
Chris Lattner268c1392003-06-22 20:25:27 +0000267 //
Chris Lattnera5434ca2003-06-22 20:10:28 +0000268 std::map<Value*, Value*> ValueMapping;
269
270 BasicBlock::iterator BI = DestBlock->begin();
271 bool HadPHINodes = isa<PHINode>(BI);
272 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
273 ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
274
275 // Clone the non-phi instructions of the dest block into the source block,
276 // keeping track of the mapping...
277 //
278 for (; BI != DestBlock->end(); ++BI) {
279 Instruction *New = BI->clone();
280 New->setName(BI->getName());
281 SourceBlock->getInstList().push_back(New);
282 ValueMapping[BI] = New;
283 }
284
285 // Now that we have built the mapping information and cloned all of the
286 // instructions (giving us a new terminator, among other things), walk the new
287 // instructions, rewriting references of old instructions to use new
288 // instructions.
289 //
290 BI = Branch; ++BI; // Get an iterator to the first new instruction
291 for (; BI != SourceBlock->end(); ++BI)
292 for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
293 if (Value *Remapped = ValueMapping[BI->getOperand(i)])
294 BI->setOperand(i, Remapped);
295
296 // Next we check to see if any of the successors of DestBlock had PHI nodes.
297 // If so, we need to add entries to the PHI nodes for SourceBlock now.
298 for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
299 SI != SE; ++SI) {
300 BasicBlock *Succ = *SI;
Reid Spencer66149462004-09-15 17:06:42 +0000301 for (BasicBlock::iterator PNI = Succ->begin(); isa<PHINode>(PNI); ++PNI) {
302 PHINode *PN = cast<PHINode>(PNI);
Chris Lattnera5434ca2003-06-22 20:10:28 +0000303 // Ok, we have a PHI node. Figure out what the incoming value was for the
304 // DestBlock.
305 Value *IV = PN->getIncomingValueForBlock(DestBlock);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000306
Chris Lattnera5434ca2003-06-22 20:10:28 +0000307 // Remap the value if necessary...
308 if (Value *MappedIV = ValueMapping[IV])
309 IV = MappedIV;
310 PN->addIncoming(IV, SourceBlock);
311 }
312 }
Chris Lattner95057f62004-03-16 23:29:09 +0000313
314 // Next, remove the old branch instruction, and any PHI node entries that we
315 // had.
316 BI = Branch; ++BI; // Get an iterator to the first new instruction
317 DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
318 SourceBlock->getInstList().erase(Branch); // Destroy the uncond branch...
Chris Lattnera5434ca2003-06-22 20:10:28 +0000319
320 // Final step: now that we have finished everything up, walk the cloned
321 // instructions one last time, constant propagating and DCE'ing them, because
322 // they may not be needed anymore.
323 //
Chris Lattnera5434ca2003-06-22 20:10:28 +0000324 if (HadPHINodes)
325 while (BI != SourceBlock->end())
326 if (!dceInstruction(BI) && !doConstantPropagation(BI))
327 ++BI;
328
Chris Lattnera5434ca2003-06-22 20:10:28 +0000329 ++NumEliminated; // We just killed a branch!
330}