blob: 40da808f671d4252da4235e70e0052add6736ceb [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//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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
Chris Lattnere03ca2c2006-09-27 04:58:23 +000021#define DEBUG_TYPE "tailduplicate"
Chris Lattnera5434ca2003-06-22 20:10:28 +000022#include "llvm/Transforms/Scalar.h"
Chris Lattner1c884e12003-08-31 21:17:44 +000023#include "llvm/Constant.h"
Chris Lattnera5434ca2003-06-22 20:10:28 +000024#include "llvm/Function.h"
Misha Brukman2b3387a2004-07-29 17:05:13 +000025#include "llvm/Instructions.h"
Chris Lattner540e5f92004-11-22 17:23:57 +000026#include "llvm/IntrinsicInst.h"
Chris Lattnera5434ca2003-06-22 20:10:28 +000027#include "llvm/Pass.h"
28#include "llvm/Type.h"
29#include "llvm/Support/CFG.h"
30#include "llvm/Transforms/Utils/Local.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000031#include "llvm/Support/CommandLine.h"
Reid Spencer557ab152007-02-05 23:32:05 +000032#include "llvm/Support/Compiler.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000033#include "llvm/Support/Debug.h"
34#include "llvm/ADT/Statistic.h"
Dan Gohman99885692008-03-21 23:51:57 +000035#include <map>
Chris Lattner49525f82004-01-09 06:02:20 +000036using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000037
Chris Lattner79a42ac2006-12-19 21:40:18 +000038STATISTIC(NumEliminated, "Number of unconditional branches eliminated");
39
Dan Gohmand78c4002008-05-13 00:00:25 +000040static cl::opt<unsigned>
41Threshold("taildup-threshold", cl::desc("Max block size to tail duplicate"),
42 cl::init(6), cl::Hidden);
43
Chris Lattnera5434ca2003-06-22 20:10:28 +000044namespace {
Reid Spencer557ab152007-02-05 23:32:05 +000045 class VISIBILITY_HIDDEN TailDup : public FunctionPass {
Chris Lattnera5434ca2003-06-22 20:10:28 +000046 bool runOnFunction(Function &F);
Devang Patel09f162c2007-05-01 21:15:47 +000047 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +000048 static char ID; // Pass identification, replacement for typeid
Devang Patel09f162c2007-05-01 21:15:47 +000049 TailDup() : FunctionPass((intptr_t)&ID) {}
50
Chris Lattnera5434ca2003-06-22 20:10:28 +000051 private:
52 inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
53 inline void eliminateUnconditionalBranch(BranchInst *BI);
Chris Lattnera5434ca2003-06-22 20:10:28 +000054 };
Chris Lattnera5434ca2003-06-22 20:10:28 +000055}
56
Dan Gohmand78c4002008-05-13 00:00:25 +000057char TailDup::ID = 0;
58static RegisterPass<TailDup> X("tailduplicate", "Tail Duplication");
59
Brian Gaeke960707c2003-11-11 22:41:34 +000060// Public interface to the Tail Duplication pass
Chris Lattner3e860842004-09-20 04:43:15 +000061FunctionPass *llvm::createTailDuplicationPass() { return new TailDup(); }
Chris Lattnera5434ca2003-06-22 20:10:28 +000062
63/// runOnFunction - Top level algorithm - Loop over each unconditional branch in
64/// the function, eliminating it if it looks attractive enough.
65///
66bool TailDup::runOnFunction(Function &F) {
67 bool Changed = false;
68 for (Function::iterator I = F.begin(), E = F.end(); I != E; )
Chris Lattner95057f62004-03-16 23:29:09 +000069 if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
Chris Lattnera5434ca2003-06-22 20:10:28 +000070 eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
71 Changed = true;
72 } else {
73 ++I;
74 }
75 return Changed;
76}
77
78/// shouldEliminateUnconditionalBranch - Return true if this branch looks
79/// attractive to eliminate. We eliminate the branch if the destination basic
80/// block has <= 5 instructions in it, not counting PHI nodes. In practice,
81/// since one of these is a terminator instruction, this means that we will add
82/// up to 4 instructions to the new block.
83///
84/// We don't count PHI nodes in the count since they will be removed when the
85/// contents of the block are copied over.
86///
87bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
88 BranchInst *BI = dyn_cast<BranchInst>(TI);
89 if (!BI || !BI->isUnconditional()) return false; // Not an uncond branch!
90
91 BasicBlock *Dest = BI->getSuccessor(0);
92 if (Dest == BI->getParent()) return false; // Do not loop infinitely!
93
Chris Lattnerd78ebd02003-07-23 03:32:41 +000094 // Do not inline a block if we will just get another branch to the same block!
Chris Lattnera64923a2004-03-16 19:45:22 +000095 TerminatorInst *DTI = Dest->getTerminator();
96 if (BranchInst *DBI = dyn_cast<BranchInst>(DTI))
Chris Lattnerd78ebd02003-07-23 03:32:41 +000097 if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
98 return false; // Do not loop infinitely!
99
Chris Lattner95057f62004-03-16 23:29:09 +0000100 // FIXME: DemoteRegToStack cannot yet demote invoke instructions to the stack,
101 // because doing so would require breaking critical edges. This should be
102 // fixed eventually.
103 if (!DTI->use_empty())
104 return false;
105
Chris Lattnera5434ca2003-06-22 20:10:28 +0000106 // Do not bother working on dead blocks...
107 pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
108 if (PI == PE && Dest != Dest->getParent()->begin())
109 return false; // It's just a dead block, ignore it...
110
111 // Also, do not bother with blocks with only a single predecessor: simplify
112 // CFG will fold these two blocks together!
113 ++PI;
114 if (PI == PE) return false; // Exactly one predecessor!
115
116 BasicBlock::iterator I = Dest->begin();
117 while (isa<PHINode>(*I)) ++I;
118
Chris Lattner540e5f92004-11-22 17:23:57 +0000119 for (unsigned Size = 0; I != Dest->end(); ++I) {
120 if (Size == Threshold) return false; // The block is too large.
Chris Lattnerce8c6262007-11-04 06:37:55 +0000121
122 // Don't tail duplicate call instructions. They are very large compared to
123 // other instructions.
124 if (isa<CallInst>(I) || isa<InvokeInst>(I)) return false;
125
Chris Lattner540e5f92004-11-22 17:23:57 +0000126 // Only count instructions that are not debugger intrinsics.
127 if (!isa<DbgInfoIntrinsic>(I)) ++Size;
128 }
Chris Lattnera64923a2004-03-16 19:45:22 +0000129
130 // Do not tail duplicate a block that has thousands of successors into a block
131 // with a single successor if the block has many other predecessors. This can
132 // cause an N^2 explosion in CFG edges (and PHI node entries), as seen in
133 // cases that have a large number of indirect gotos.
Chris Lattner8af74242004-11-01 07:05:07 +0000134 unsigned NumSuccs = DTI->getNumSuccessors();
135 if (NumSuccs > 8) {
136 unsigned TooMany = 128;
137 if (NumSuccs >= TooMany) return false;
138 TooMany = TooMany/NumSuccs;
139 for (; PI != PE; ++PI)
140 if (TooMany-- == 0) return false;
141 }
Chris Lattnerc4650462006-09-07 21:30:15 +0000142
143 // Finally, if this unconditional branch is a fall-through, be careful about
144 // tail duplicating it. In particular, we don't want to taildup it if the
145 // original block will still be there after taildup is completed: doing so
146 // would eliminate the fall-through, requiring unconditional branches.
147 Function::iterator DestI = Dest;
148 if (&*--DestI == BI->getParent()) {
149 // The uncond branch is a fall-through. Tail duplication of the block is
150 // will eliminate the fall-through-ness and end up cloning the terminator
151 // at the end of the Dest block. Since the original Dest block will
152 // continue to exist, this means that one or the other will not be able to
153 // fall through. One typical example that this helps with is code like:
154 // if (a)
155 // foo();
156 // if (b)
157 // foo();
158 // Cloning the 'if b' block into the end of the first foo block is messy.
Chris Lattnerd1f8e072006-09-10 18:17:58 +0000159
160 // The messy case is when the fall-through block falls through to other
161 // blocks. This is what we would be preventing if we cloned the block.
162 DestI = Dest;
163 if (++DestI != Dest->getParent()->end()) {
164 BasicBlock *DestSucc = DestI;
165 // If any of Dest's successors are fall-throughs, don't do this xform.
166 for (succ_iterator SI = succ_begin(Dest), SE = succ_end(Dest);
167 SI != SE; ++SI)
168 if (*SI == DestSucc)
169 return false;
170 }
Chris Lattnerc4650462006-09-07 21:30:15 +0000171 }
Chris Lattnera64923a2004-03-16 19:45:22 +0000172
Misha Brukmanb1c93172005-04-21 23:48:37 +0000173 return true;
Chris Lattnera5434ca2003-06-22 20:10:28 +0000174}
175
Chris Lattner2ce32df2004-10-06 03:27:37 +0000176/// FindObviousSharedDomOf - We know there is a branch from SrcBlock to
177/// DestBlock, and that SrcBlock is not the only predecessor of DstBlock. If we
178/// can find a predecessor of SrcBlock that is a dominator of both SrcBlock and
179/// DstBlock, return it.
180static BasicBlock *FindObviousSharedDomOf(BasicBlock *SrcBlock,
181 BasicBlock *DstBlock) {
182 // SrcBlock must have a single predecessor.
183 pred_iterator PI = pred_begin(SrcBlock), PE = pred_end(SrcBlock);
184 if (PI == PE || ++PI != PE) return 0;
185
186 BasicBlock *SrcPred = *pred_begin(SrcBlock);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000187
Chris Lattner2ce32df2004-10-06 03:27:37 +0000188 // Look at the predecessors of DstBlock. One of them will be SrcBlock. If
189 // there is only one other pred, get it, otherwise we can't handle it.
190 PI = pred_begin(DstBlock); PE = pred_end(DstBlock);
191 BasicBlock *DstOtherPred = 0;
192 if (*PI == SrcBlock) {
193 if (++PI == PE) return 0;
194 DstOtherPred = *PI;
195 if (++PI != PE) return 0;
196 } else {
197 DstOtherPred = *PI;
198 if (++PI == PE || *PI != SrcBlock || ++PI != PE) return 0;
199 }
200
201 // We can handle two situations here: "if then" and "if then else" blocks. An
202 // 'if then' situation is just where DstOtherPred == SrcPred.
203 if (DstOtherPred == SrcPred)
204 return SrcPred;
205
206 // Check to see if we have an "if then else" situation, which means that
207 // DstOtherPred will have a single predecessor and it will be SrcPred.
208 PI = pred_begin(DstOtherPred); PE = pred_end(DstOtherPred);
209 if (PI != PE && *PI == SrcPred) {
210 if (++PI != PE) return 0; // Not a single pred.
211 return SrcPred; // Otherwise, it's an "if then" situation. Return the if.
212 }
213
214 // Otherwise, this is something we can't handle.
215 return 0;
216}
217
Chris Lattnera5434ca2003-06-22 20:10:28 +0000218
219/// eliminateUnconditionalBranch - Clone the instructions from the destination
220/// block into the source block, eliminating the specified unconditional branch.
221/// If the destination block defines values used by successors of the dest
222/// block, we may need to insert PHI nodes.
223///
224void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
225 BasicBlock *SourceBlock = Branch->getParent();
226 BasicBlock *DestBlock = Branch->getSuccessor(0);
227 assert(SourceBlock != DestBlock && "Our predicate is broken!");
228
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000229 DOUT << "TailDuplication[" << SourceBlock->getParent()->getName()
230 << "]: Eliminating branch: " << *Branch;
Chris Lattnera5434ca2003-06-22 20:10:28 +0000231
Chris Lattner2ce32df2004-10-06 03:27:37 +0000232 // See if we can avoid duplicating code by moving it up to a dominator of both
233 // blocks.
234 if (BasicBlock *DomBlock = FindObviousSharedDomOf(SourceBlock, DestBlock)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000235 DOUT << "Found shared dominator: " << DomBlock->getName() << "\n";
Chris Lattner2ce32df2004-10-06 03:27:37 +0000236
237 // If there are non-phi instructions in DestBlock that have no operands
238 // defined in DestBlock, and if the instruction has no side effects, we can
239 // move the instruction to DomBlock instead of duplicating it.
240 BasicBlock::iterator BBI = DestBlock->begin();
241 while (isa<PHINode>(BBI)) ++BBI;
242 while (!isa<TerminatorInst>(BBI)) {
243 Instruction *I = BBI++;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000244
Chris Lattner2ce32df2004-10-06 03:27:37 +0000245 bool CanHoist = !I->isTrapping() && !I->mayWriteToMemory();
246 if (CanHoist) {
247 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
248 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(op)))
249 if (OpI->getParent() == DestBlock ||
250 (isa<InvokeInst>(OpI) && OpI->getParent() == DomBlock)) {
251 CanHoist = false;
252 break;
253 }
254 if (CanHoist) {
255 // Remove from DestBlock, move right before the term in DomBlock.
256 DestBlock->getInstList().remove(I);
257 DomBlock->getInstList().insert(DomBlock->getTerminator(), I);
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000258 DOUT << "Hoisted: " << *I;
Chris Lattner2ce32df2004-10-06 03:27:37 +0000259 }
260 }
261 }
262 }
263
Chris Lattner95057f62004-03-16 23:29:09 +0000264 // Tail duplication can not update SSA properties correctly if the values
265 // defined in the duplicated tail are used outside of the tail itself. For
266 // this reason, we spill all values that are used outside of the tail to the
267 // stack.
268 for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
Chris Lattner567166c2008-04-20 22:18:22 +0000269 if (I->isUsedOutsideOfBlock(DestBlock)) {
270 // We found a use outside of the tail. Create a new stack slot to
271 // break this inter-block usage pattern.
272 DemoteRegToStack(*I);
Chris Lattner95057f62004-03-16 23:29:09 +0000273 }
274
Chris Lattnera5434ca2003-06-22 20:10:28 +0000275 // We are going to have to map operands from the original block B to the new
276 // copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
277 // nodes also define part of this mapping. Loop over these PHI nodes, adding
278 // them to our mapping.
Chris Lattner268c1392003-06-22 20:25:27 +0000279 //
Chris Lattnera5434ca2003-06-22 20:10:28 +0000280 std::map<Value*, Value*> ValueMapping;
281
282 BasicBlock::iterator BI = DestBlock->begin();
283 bool HadPHINodes = isa<PHINode>(BI);
284 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
285 ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
286
287 // Clone the non-phi instructions of the dest block into the source block,
288 // keeping track of the mapping...
289 //
290 for (; BI != DestBlock->end(); ++BI) {
291 Instruction *New = BI->clone();
Owen Anderson7629b712008-04-14 17:38:21 +0000292 New->setName(BI->getName());
Chris Lattnera5434ca2003-06-22 20:10:28 +0000293 SourceBlock->getInstList().push_back(New);
294 ValueMapping[BI] = New;
295 }
296
297 // Now that we have built the mapping information and cloned all of the
298 // instructions (giving us a new terminator, among other things), walk the new
299 // instructions, rewriting references of old instructions to use new
300 // instructions.
301 //
302 BI = Branch; ++BI; // Get an iterator to the first new instruction
303 for (; BI != SourceBlock->end(); ++BI)
304 for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
305 if (Value *Remapped = ValueMapping[BI->getOperand(i)])
306 BI->setOperand(i, Remapped);
307
308 // Next we check to see if any of the successors of DestBlock had PHI nodes.
309 // If so, we need to add entries to the PHI nodes for SourceBlock now.
310 for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
311 SI != SE; ++SI) {
312 BasicBlock *Succ = *SI;
Reid Spencer66149462004-09-15 17:06:42 +0000313 for (BasicBlock::iterator PNI = Succ->begin(); isa<PHINode>(PNI); ++PNI) {
314 PHINode *PN = cast<PHINode>(PNI);
Chris Lattnera5434ca2003-06-22 20:10:28 +0000315 // Ok, we have a PHI node. Figure out what the incoming value was for the
316 // DestBlock.
317 Value *IV = PN->getIncomingValueForBlock(DestBlock);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000318
Chris Lattnera5434ca2003-06-22 20:10:28 +0000319 // Remap the value if necessary...
320 if (Value *MappedIV = ValueMapping[IV])
321 IV = MappedIV;
322 PN->addIncoming(IV, SourceBlock);
323 }
324 }
Chris Lattner95057f62004-03-16 23:29:09 +0000325
326 // Next, remove the old branch instruction, and any PHI node entries that we
327 // had.
328 BI = Branch; ++BI; // Get an iterator to the first new instruction
329 DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
330 SourceBlock->getInstList().erase(Branch); // Destroy the uncond branch...
Chris Lattnera5434ca2003-06-22 20:10:28 +0000331
332 // Final step: now that we have finished everything up, walk the cloned
333 // instructions one last time, constant propagating and DCE'ing them, because
334 // they may not be needed anymore.
335 //
Chris Lattnera5434ca2003-06-22 20:10:28 +0000336 if (HadPHINodes)
337 while (BI != SourceBlock->end())
338 if (!dceInstruction(BI) && !doConstantPropagation(BI))
339 ++BI;
340
Chris Lattnera5434ca2003-06-22 20:10:28 +0000341 ++NumEliminated; // We just killed a branch!
342}