blob: 43aaced37892527164f0787d6f230eb0453e7679 [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 Lattnerc597b8a2006-01-22 23:32:06 +000033#include <iostream>
Chris Lattner49525f82004-01-09 06:02:20 +000034using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000035
Chris Lattnera5434ca2003-06-22 20:10:28 +000036namespace {
Chris Lattnerc14da962004-04-18 00:52:43 +000037 cl::opt<unsigned>
38 Threshold("taildup-threshold", cl::desc("Max block size to tail duplicate"),
39 cl::init(6), cl::Hidden);
Chris Lattnera5434ca2003-06-22 20:10:28 +000040 Statistic<> NumEliminated("tailduplicate",
41 "Number of unconditional branches eliminated");
42 Statistic<> NumPHINodes("tailduplicate", "Number of phi nodes inserted");
43
44 class TailDup : public FunctionPass {
45 bool runOnFunction(Function &F);
46 private:
47 inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
48 inline void eliminateUnconditionalBranch(BranchInst *BI);
Chris Lattnera5434ca2003-06-22 20:10:28 +000049 };
Chris Lattnerc2d3d312006-08-27 22:42:52 +000050 RegisterPass<TailDup> X("tailduplicate", "Tail Duplication");
Chris Lattnera5434ca2003-06-22 20:10:28 +000051}
52
Brian Gaeke960707c2003-11-11 22:41:34 +000053// Public interface to the Tail Duplication pass
Chris Lattner3e860842004-09-20 04:43:15 +000054FunctionPass *llvm::createTailDuplicationPass() { return new TailDup(); }
Chris Lattnera5434ca2003-06-22 20:10:28 +000055
56/// runOnFunction - Top level algorithm - Loop over each unconditional branch in
57/// the function, eliminating it if it looks attractive enough.
58///
59bool TailDup::runOnFunction(Function &F) {
60 bool Changed = false;
61 for (Function::iterator I = F.begin(), E = F.end(); I != E; )
Chris Lattner95057f62004-03-16 23:29:09 +000062 if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
Chris Lattnera5434ca2003-06-22 20:10:28 +000063 eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
64 Changed = true;
65 } else {
66 ++I;
67 }
68 return Changed;
69}
70
71/// shouldEliminateUnconditionalBranch - Return true if this branch looks
72/// attractive to eliminate. We eliminate the branch if the destination basic
73/// block has <= 5 instructions in it, not counting PHI nodes. In practice,
74/// since one of these is a terminator instruction, this means that we will add
75/// up to 4 instructions to the new block.
76///
77/// We don't count PHI nodes in the count since they will be removed when the
78/// contents of the block are copied over.
79///
80bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
81 BranchInst *BI = dyn_cast<BranchInst>(TI);
82 if (!BI || !BI->isUnconditional()) return false; // Not an uncond branch!
83
84 BasicBlock *Dest = BI->getSuccessor(0);
85 if (Dest == BI->getParent()) return false; // Do not loop infinitely!
86
Chris Lattnerd78ebd02003-07-23 03:32:41 +000087 // Do not inline a block if we will just get another branch to the same block!
Chris Lattnera64923a2004-03-16 19:45:22 +000088 TerminatorInst *DTI = Dest->getTerminator();
89 if (BranchInst *DBI = dyn_cast<BranchInst>(DTI))
Chris Lattnerd78ebd02003-07-23 03:32:41 +000090 if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
91 return false; // Do not loop infinitely!
92
Chris Lattner95057f62004-03-16 23:29:09 +000093 // FIXME: DemoteRegToStack cannot yet demote invoke instructions to the stack,
94 // because doing so would require breaking critical edges. This should be
95 // fixed eventually.
96 if (!DTI->use_empty())
97 return false;
98
Chris Lattnera5434ca2003-06-22 20:10:28 +000099 // Do not bother working on dead blocks...
100 pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
101 if (PI == PE && Dest != Dest->getParent()->begin())
102 return false; // It's just a dead block, ignore it...
103
104 // Also, do not bother with blocks with only a single predecessor: simplify
105 // CFG will fold these two blocks together!
106 ++PI;
107 if (PI == PE) return false; // Exactly one predecessor!
108
109 BasicBlock::iterator I = Dest->begin();
110 while (isa<PHINode>(*I)) ++I;
111
Chris Lattner540e5f92004-11-22 17:23:57 +0000112 for (unsigned Size = 0; I != Dest->end(); ++I) {
113 if (Size == Threshold) return false; // The block is too large.
114 // Only count instructions that are not debugger intrinsics.
115 if (!isa<DbgInfoIntrinsic>(I)) ++Size;
116 }
Chris Lattnera64923a2004-03-16 19:45:22 +0000117
118 // Do not tail duplicate a block that has thousands of successors into a block
119 // with a single successor if the block has many other predecessors. This can
120 // cause an N^2 explosion in CFG edges (and PHI node entries), as seen in
121 // cases that have a large number of indirect gotos.
Chris Lattner8af74242004-11-01 07:05:07 +0000122 unsigned NumSuccs = DTI->getNumSuccessors();
123 if (NumSuccs > 8) {
124 unsigned TooMany = 128;
125 if (NumSuccs >= TooMany) return false;
126 TooMany = TooMany/NumSuccs;
127 for (; PI != PE; ++PI)
128 if (TooMany-- == 0) return false;
129 }
Chris Lattnerc4650462006-09-07 21:30:15 +0000130
131 // Finally, if this unconditional branch is a fall-through, be careful about
132 // tail duplicating it. In particular, we don't want to taildup it if the
133 // original block will still be there after taildup is completed: doing so
134 // would eliminate the fall-through, requiring unconditional branches.
135 Function::iterator DestI = Dest;
136 if (&*--DestI == BI->getParent()) {
137 // The uncond branch is a fall-through. Tail duplication of the block is
138 // will eliminate the fall-through-ness and end up cloning the terminator
139 // at the end of the Dest block. Since the original Dest block will
140 // continue to exist, this means that one or the other will not be able to
141 // fall through. One typical example that this helps with is code like:
142 // if (a)
143 // foo();
144 // if (b)
145 // foo();
146 // Cloning the 'if b' block into the end of the first foo block is messy.
147 return false;
148 }
Chris Lattnera64923a2004-03-16 19:45:22 +0000149
Misha Brukmanb1c93172005-04-21 23:48:37 +0000150 return true;
Chris Lattnera5434ca2003-06-22 20:10:28 +0000151}
152
Chris Lattner2ce32df2004-10-06 03:27:37 +0000153/// FindObviousSharedDomOf - We know there is a branch from SrcBlock to
154/// DestBlock, and that SrcBlock is not the only predecessor of DstBlock. If we
155/// can find a predecessor of SrcBlock that is a dominator of both SrcBlock and
156/// DstBlock, return it.
157static BasicBlock *FindObviousSharedDomOf(BasicBlock *SrcBlock,
158 BasicBlock *DstBlock) {
159 // SrcBlock must have a single predecessor.
160 pred_iterator PI = pred_begin(SrcBlock), PE = pred_end(SrcBlock);
161 if (PI == PE || ++PI != PE) return 0;
162
163 BasicBlock *SrcPred = *pred_begin(SrcBlock);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000164
Chris Lattner2ce32df2004-10-06 03:27:37 +0000165 // Look at the predecessors of DstBlock. One of them will be SrcBlock. If
166 // there is only one other pred, get it, otherwise we can't handle it.
167 PI = pred_begin(DstBlock); PE = pred_end(DstBlock);
168 BasicBlock *DstOtherPred = 0;
169 if (*PI == SrcBlock) {
170 if (++PI == PE) return 0;
171 DstOtherPred = *PI;
172 if (++PI != PE) return 0;
173 } else {
174 DstOtherPred = *PI;
175 if (++PI == PE || *PI != SrcBlock || ++PI != PE) return 0;
176 }
177
178 // We can handle two situations here: "if then" and "if then else" blocks. An
179 // 'if then' situation is just where DstOtherPred == SrcPred.
180 if (DstOtherPred == SrcPred)
181 return SrcPred;
182
183 // Check to see if we have an "if then else" situation, which means that
184 // DstOtherPred will have a single predecessor and it will be SrcPred.
185 PI = pred_begin(DstOtherPred); PE = pred_end(DstOtherPred);
186 if (PI != PE && *PI == SrcPred) {
187 if (++PI != PE) return 0; // Not a single pred.
188 return SrcPred; // Otherwise, it's an "if then" situation. Return the if.
189 }
190
191 // Otherwise, this is something we can't handle.
192 return 0;
193}
194
Chris Lattnera5434ca2003-06-22 20:10:28 +0000195
196/// eliminateUnconditionalBranch - Clone the instructions from the destination
197/// block into the source block, eliminating the specified unconditional branch.
198/// If the destination block defines values used by successors of the dest
199/// block, we may need to insert PHI nodes.
200///
201void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
202 BasicBlock *SourceBlock = Branch->getParent();
203 BasicBlock *DestBlock = Branch->getSuccessor(0);
204 assert(SourceBlock != DestBlock && "Our predicate is broken!");
205
206 DEBUG(std::cerr << "TailDuplication[" << SourceBlock->getParent()->getName()
207 << "]: Eliminating branch: " << *Branch);
208
Chris Lattner2ce32df2004-10-06 03:27:37 +0000209 // See if we can avoid duplicating code by moving it up to a dominator of both
210 // blocks.
211 if (BasicBlock *DomBlock = FindObviousSharedDomOf(SourceBlock, DestBlock)) {
212 DEBUG(std::cerr << "Found shared dominator: " << DomBlock->getName()
213 << "\n");
214
215 // If there are non-phi instructions in DestBlock that have no operands
216 // defined in DestBlock, and if the instruction has no side effects, we can
217 // move the instruction to DomBlock instead of duplicating it.
218 BasicBlock::iterator BBI = DestBlock->begin();
219 while (isa<PHINode>(BBI)) ++BBI;
220 while (!isa<TerminatorInst>(BBI)) {
221 Instruction *I = BBI++;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000222
Chris Lattner2ce32df2004-10-06 03:27:37 +0000223 bool CanHoist = !I->isTrapping() && !I->mayWriteToMemory();
224 if (CanHoist) {
225 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
226 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(op)))
227 if (OpI->getParent() == DestBlock ||
228 (isa<InvokeInst>(OpI) && OpI->getParent() == DomBlock)) {
229 CanHoist = false;
230 break;
231 }
232 if (CanHoist) {
233 // Remove from DestBlock, move right before the term in DomBlock.
234 DestBlock->getInstList().remove(I);
235 DomBlock->getInstList().insert(DomBlock->getTerminator(), I);
236 DEBUG(std::cerr << "Hoisted: " << *I);
237 }
238 }
239 }
240 }
241
Chris Lattner95057f62004-03-16 23:29:09 +0000242 // Tail duplication can not update SSA properties correctly if the values
243 // defined in the duplicated tail are used outside of the tail itself. For
244 // this reason, we spill all values that are used outside of the tail to the
245 // stack.
246 for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
247 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
248 ++UI) {
249 bool ShouldDemote = false;
250 if (cast<Instruction>(*UI)->getParent() != DestBlock) {
251 // We must allow our successors to use tail values in their PHI nodes
252 // (if the incoming value corresponds to the tail block).
253 if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
254 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
255 if (PN->getIncomingValue(i) == I &&
256 PN->getIncomingBlock(i) != DestBlock) {
257 ShouldDemote = true;
258 break;
259 }
260
261 } else {
262 ShouldDemote = true;
263 }
264 } else if (PHINode *PN = dyn_cast<PHINode>(cast<Instruction>(*UI))) {
265 // If the user of this instruction is a PHI node in the current block,
Chris Lattnera3783a52004-03-16 23:36:49 +0000266 // which has an entry from another block using the value, spill it.
267 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
268 if (PN->getIncomingValue(i) == I &&
269 PN->getIncomingBlock(i) != DestBlock) {
270 ShouldDemote = true;
271 break;
272 }
Chris Lattner95057f62004-03-16 23:29:09 +0000273 }
274
275 if (ShouldDemote) {
276 // We found a use outside of the tail. Create a new stack slot to
277 // break this inter-block usage pattern.
278 DemoteRegToStack(*I);
279 break;
280 }
281 }
282
Chris Lattnera5434ca2003-06-22 20:10:28 +0000283 // We are going to have to map operands from the original block B to the new
284 // copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
285 // nodes also define part of this mapping. Loop over these PHI nodes, adding
286 // them to our mapping.
Chris Lattner268c1392003-06-22 20:25:27 +0000287 //
Chris Lattnera5434ca2003-06-22 20:10:28 +0000288 std::map<Value*, Value*> ValueMapping;
289
290 BasicBlock::iterator BI = DestBlock->begin();
291 bool HadPHINodes = isa<PHINode>(BI);
292 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
293 ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
294
295 // Clone the non-phi instructions of the dest block into the source block,
296 // keeping track of the mapping...
297 //
298 for (; BI != DestBlock->end(); ++BI) {
299 Instruction *New = BI->clone();
300 New->setName(BI->getName());
301 SourceBlock->getInstList().push_back(New);
302 ValueMapping[BI] = New;
303 }
304
305 // Now that we have built the mapping information and cloned all of the
306 // instructions (giving us a new terminator, among other things), walk the new
307 // instructions, rewriting references of old instructions to use new
308 // instructions.
309 //
310 BI = Branch; ++BI; // Get an iterator to the first new instruction
311 for (; BI != SourceBlock->end(); ++BI)
312 for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
313 if (Value *Remapped = ValueMapping[BI->getOperand(i)])
314 BI->setOperand(i, Remapped);
315
316 // Next we check to see if any of the successors of DestBlock had PHI nodes.
317 // If so, we need to add entries to the PHI nodes for SourceBlock now.
318 for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
319 SI != SE; ++SI) {
320 BasicBlock *Succ = *SI;
Reid Spencer66149462004-09-15 17:06:42 +0000321 for (BasicBlock::iterator PNI = Succ->begin(); isa<PHINode>(PNI); ++PNI) {
322 PHINode *PN = cast<PHINode>(PNI);
Chris Lattnera5434ca2003-06-22 20:10:28 +0000323 // Ok, we have a PHI node. Figure out what the incoming value was for the
324 // DestBlock.
325 Value *IV = PN->getIncomingValueForBlock(DestBlock);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000326
Chris Lattnera5434ca2003-06-22 20:10:28 +0000327 // Remap the value if necessary...
328 if (Value *MappedIV = ValueMapping[IV])
329 IV = MappedIV;
330 PN->addIncoming(IV, SourceBlock);
331 }
332 }
Chris Lattner95057f62004-03-16 23:29:09 +0000333
334 // Next, remove the old branch instruction, and any PHI node entries that we
335 // had.
336 BI = Branch; ++BI; // Get an iterator to the first new instruction
337 DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
338 SourceBlock->getInstList().erase(Branch); // Destroy the uncond branch...
Chris Lattnera5434ca2003-06-22 20:10:28 +0000339
340 // Final step: now that we have finished everything up, walk the cloned
341 // instructions one last time, constant propagating and DCE'ing them, because
342 // they may not be needed anymore.
343 //
Chris Lattnera5434ca2003-06-22 20:10:28 +0000344 if (HadPHINodes)
345 while (BI != SourceBlock->end())
346 if (!dceInstruction(BI) && !doConstantPropagation(BI))
347 ++BI;
348
Chris Lattnera5434ca2003-06-22 20:10:28 +0000349 ++NumEliminated; // We just killed a branch!
350}