blob: 877e67469943b64e4f42a17302ef22efd9e7f07a [file] [log] [blame]
Chris Lattner7a7bef42003-06-22 20:10:28 +00001//===- TailDuplication.cpp - Simplify CFG through tail duplication --------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner7a7bef42003-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 Lattner75144372006-09-27 04:58:23 +000021#define DEBUG_TYPE "tailduplicate"
Chris Lattner7a7bef42003-06-22 20:10:28 +000022#include "llvm/Transforms/Scalar.h"
Chris Lattner3186d272003-08-31 21:17:44 +000023#include "llvm/Constant.h"
Chris Lattner7a7bef42003-06-22 20:10:28 +000024#include "llvm/Function.h"
Misha Brukmand8e1eea2004-07-29 17:05:13 +000025#include "llvm/Instructions.h"
Chris Lattnerb9df9b42004-11-22 17:23:57 +000026#include "llvm/IntrinsicInst.h"
Chris Lattner7a7bef42003-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 Spencer551ccae2004-09-01 22:55:40 +000031#include "llvm/Support/CommandLine.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000032#include "llvm/Support/Compiler.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/Support/Debug.h"
34#include "llvm/ADT/Statistic.h"
Chris Lattnerd7456022004-01-09 06:02:20 +000035using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000036
Chris Lattner0e5f4992006-12-19 21:40:18 +000037STATISTIC(NumEliminated, "Number of unconditional branches eliminated");
38
Chris Lattner7a7bef42003-06-22 20:10:28 +000039namespace {
Chris Lattner3c85eef2004-04-18 00:52:43 +000040 cl::opt<unsigned>
41 Threshold("taildup-threshold", cl::desc("Max block size to tail duplicate"),
42 cl::init(6), cl::Hidden);
Reid Spencer9133fe22007-02-05 23:32:05 +000043 class VISIBILITY_HIDDEN TailDup : public FunctionPass {
Chris Lattner7a7bef42003-06-22 20:10:28 +000044 bool runOnFunction(Function &F);
Devang Patel794fd752007-05-01 21:15:47 +000045 public:
Devang Patel19974732007-05-03 01:11:54 +000046 static char ID; // Pass identifcation, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000047 TailDup() : FunctionPass((intptr_t)&ID) {}
48
Chris Lattner7a7bef42003-06-22 20:10:28 +000049 private:
50 inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
51 inline void eliminateUnconditionalBranch(BranchInst *BI);
Chris Lattner7a7bef42003-06-22 20:10:28 +000052 };
Devang Patel19974732007-05-03 01:11:54 +000053 char TailDup::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +000054 RegisterPass<TailDup> X("tailduplicate", "Tail Duplication");
Chris Lattner7a7bef42003-06-22 20:10:28 +000055}
56
Brian Gaeked0fde302003-11-11 22:41:34 +000057// Public interface to the Tail Duplication pass
Chris Lattner4b501562004-09-20 04:43:15 +000058FunctionPass *llvm::createTailDuplicationPass() { return new TailDup(); }
Chris Lattner7a7bef42003-06-22 20:10:28 +000059
60/// runOnFunction - Top level algorithm - Loop over each unconditional branch in
61/// the function, eliminating it if it looks attractive enough.
62///
63bool TailDup::runOnFunction(Function &F) {
64 bool Changed = false;
65 for (Function::iterator I = F.begin(), E = F.end(); I != E; )
Chris Lattner24ad00d2004-03-16 23:29:09 +000066 if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
Chris Lattner7a7bef42003-06-22 20:10:28 +000067 eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
68 Changed = true;
69 } else {
70 ++I;
71 }
72 return Changed;
73}
74
75/// shouldEliminateUnconditionalBranch - Return true if this branch looks
76/// attractive to eliminate. We eliminate the branch if the destination basic
77/// block has <= 5 instructions in it, not counting PHI nodes. In practice,
78/// since one of these is a terminator instruction, this means that we will add
79/// up to 4 instructions to the new block.
80///
81/// We don't count PHI nodes in the count since they will be removed when the
82/// contents of the block are copied over.
83///
84bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
85 BranchInst *BI = dyn_cast<BranchInst>(TI);
86 if (!BI || !BI->isUnconditional()) return false; // Not an uncond branch!
87
88 BasicBlock *Dest = BI->getSuccessor(0);
89 if (Dest == BI->getParent()) return false; // Do not loop infinitely!
90
Chris Lattner00f185f2003-07-23 03:32:41 +000091 // Do not inline a block if we will just get another branch to the same block!
Chris Lattner4bebf082004-03-16 19:45:22 +000092 TerminatorInst *DTI = Dest->getTerminator();
93 if (BranchInst *DBI = dyn_cast<BranchInst>(DTI))
Chris Lattner00f185f2003-07-23 03:32:41 +000094 if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
95 return false; // Do not loop infinitely!
96
Chris Lattner24ad00d2004-03-16 23:29:09 +000097 // FIXME: DemoteRegToStack cannot yet demote invoke instructions to the stack,
98 // because doing so would require breaking critical edges. This should be
99 // fixed eventually.
100 if (!DTI->use_empty())
101 return false;
102
Chris Lattner7a7bef42003-06-22 20:10:28 +0000103 // Do not bother working on dead blocks...
104 pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
105 if (PI == PE && Dest != Dest->getParent()->begin())
106 return false; // It's just a dead block, ignore it...
107
108 // Also, do not bother with blocks with only a single predecessor: simplify
109 // CFG will fold these two blocks together!
110 ++PI;
111 if (PI == PE) return false; // Exactly one predecessor!
112
113 BasicBlock::iterator I = Dest->begin();
114 while (isa<PHINode>(*I)) ++I;
115
Chris Lattnerb9df9b42004-11-22 17:23:57 +0000116 for (unsigned Size = 0; I != Dest->end(); ++I) {
117 if (Size == Threshold) return false; // The block is too large.
118 // Only count instructions that are not debugger intrinsics.
119 if (!isa<DbgInfoIntrinsic>(I)) ++Size;
120 }
Chris Lattner4bebf082004-03-16 19:45:22 +0000121
122 // Do not tail duplicate a block that has thousands of successors into a block
123 // with a single successor if the block has many other predecessors. This can
124 // cause an N^2 explosion in CFG edges (and PHI node entries), as seen in
125 // cases that have a large number of indirect gotos.
Chris Lattner7e54a012004-11-01 07:05:07 +0000126 unsigned NumSuccs = DTI->getNumSuccessors();
127 if (NumSuccs > 8) {
128 unsigned TooMany = 128;
129 if (NumSuccs >= TooMany) return false;
130 TooMany = TooMany/NumSuccs;
131 for (; PI != PE; ++PI)
132 if (TooMany-- == 0) return false;
133 }
Chris Lattnere99c6232006-09-07 21:30:15 +0000134
135 // Finally, if this unconditional branch is a fall-through, be careful about
136 // tail duplicating it. In particular, we don't want to taildup it if the
137 // original block will still be there after taildup is completed: doing so
138 // would eliminate the fall-through, requiring unconditional branches.
139 Function::iterator DestI = Dest;
140 if (&*--DestI == BI->getParent()) {
141 // The uncond branch is a fall-through. Tail duplication of the block is
142 // will eliminate the fall-through-ness and end up cloning the terminator
143 // at the end of the Dest block. Since the original Dest block will
144 // continue to exist, this means that one or the other will not be able to
145 // fall through. One typical example that this helps with is code like:
146 // if (a)
147 // foo();
148 // if (b)
149 // foo();
150 // Cloning the 'if b' block into the end of the first foo block is messy.
Chris Lattnerdfa1af02006-09-10 18:17:58 +0000151
152 // The messy case is when the fall-through block falls through to other
153 // blocks. This is what we would be preventing if we cloned the block.
154 DestI = Dest;
155 if (++DestI != Dest->getParent()->end()) {
156 BasicBlock *DestSucc = DestI;
157 // If any of Dest's successors are fall-throughs, don't do this xform.
158 for (succ_iterator SI = succ_begin(Dest), SE = succ_end(Dest);
159 SI != SE; ++SI)
160 if (*SI == DestSucc)
161 return false;
162 }
Chris Lattnere99c6232006-09-07 21:30:15 +0000163 }
Chris Lattner4bebf082004-03-16 19:45:22 +0000164
Misha Brukmanfd939082005-04-21 23:48:37 +0000165 return true;
Chris Lattner7a7bef42003-06-22 20:10:28 +0000166}
167
Chris Lattnerc3e903f2004-10-06 03:27:37 +0000168/// FindObviousSharedDomOf - We know there is a branch from SrcBlock to
169/// DestBlock, and that SrcBlock is not the only predecessor of DstBlock. If we
170/// can find a predecessor of SrcBlock that is a dominator of both SrcBlock and
171/// DstBlock, return it.
172static BasicBlock *FindObviousSharedDomOf(BasicBlock *SrcBlock,
173 BasicBlock *DstBlock) {
174 // SrcBlock must have a single predecessor.
175 pred_iterator PI = pred_begin(SrcBlock), PE = pred_end(SrcBlock);
176 if (PI == PE || ++PI != PE) return 0;
177
178 BasicBlock *SrcPred = *pred_begin(SrcBlock);
Misha Brukmanfd939082005-04-21 23:48:37 +0000179
Chris Lattnerc3e903f2004-10-06 03:27:37 +0000180 // Look at the predecessors of DstBlock. One of them will be SrcBlock. If
181 // there is only one other pred, get it, otherwise we can't handle it.
182 PI = pred_begin(DstBlock); PE = pred_end(DstBlock);
183 BasicBlock *DstOtherPred = 0;
184 if (*PI == SrcBlock) {
185 if (++PI == PE) return 0;
186 DstOtherPred = *PI;
187 if (++PI != PE) return 0;
188 } else {
189 DstOtherPred = *PI;
190 if (++PI == PE || *PI != SrcBlock || ++PI != PE) return 0;
191 }
192
193 // We can handle two situations here: "if then" and "if then else" blocks. An
194 // 'if then' situation is just where DstOtherPred == SrcPred.
195 if (DstOtherPred == SrcPred)
196 return SrcPred;
197
198 // Check to see if we have an "if then else" situation, which means that
199 // DstOtherPred will have a single predecessor and it will be SrcPred.
200 PI = pred_begin(DstOtherPred); PE = pred_end(DstOtherPred);
201 if (PI != PE && *PI == SrcPred) {
202 if (++PI != PE) return 0; // Not a single pred.
203 return SrcPred; // Otherwise, it's an "if then" situation. Return the if.
204 }
205
206 // Otherwise, this is something we can't handle.
207 return 0;
208}
209
Chris Lattner7a7bef42003-06-22 20:10:28 +0000210
211/// eliminateUnconditionalBranch - Clone the instructions from the destination
212/// block into the source block, eliminating the specified unconditional branch.
213/// If the destination block defines values used by successors of the dest
214/// block, we may need to insert PHI nodes.
215///
216void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
217 BasicBlock *SourceBlock = Branch->getParent();
218 BasicBlock *DestBlock = Branch->getSuccessor(0);
219 assert(SourceBlock != DestBlock && "Our predicate is broken!");
220
Bill Wendlingb7427032006-11-26 09:46:52 +0000221 DOUT << "TailDuplication[" << SourceBlock->getParent()->getName()
222 << "]: Eliminating branch: " << *Branch;
Chris Lattner7a7bef42003-06-22 20:10:28 +0000223
Chris Lattnerc3e903f2004-10-06 03:27:37 +0000224 // See if we can avoid duplicating code by moving it up to a dominator of both
225 // blocks.
226 if (BasicBlock *DomBlock = FindObviousSharedDomOf(SourceBlock, DestBlock)) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000227 DOUT << "Found shared dominator: " << DomBlock->getName() << "\n";
Chris Lattnerc3e903f2004-10-06 03:27:37 +0000228
229 // If there are non-phi instructions in DestBlock that have no operands
230 // defined in DestBlock, and if the instruction has no side effects, we can
231 // move the instruction to DomBlock instead of duplicating it.
232 BasicBlock::iterator BBI = DestBlock->begin();
233 while (isa<PHINode>(BBI)) ++BBI;
234 while (!isa<TerminatorInst>(BBI)) {
235 Instruction *I = BBI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000236
Chris Lattnerc3e903f2004-10-06 03:27:37 +0000237 bool CanHoist = !I->isTrapping() && !I->mayWriteToMemory();
238 if (CanHoist) {
239 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
240 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(op)))
241 if (OpI->getParent() == DestBlock ||
242 (isa<InvokeInst>(OpI) && OpI->getParent() == DomBlock)) {
243 CanHoist = false;
244 break;
245 }
246 if (CanHoist) {
247 // Remove from DestBlock, move right before the term in DomBlock.
248 DestBlock->getInstList().remove(I);
249 DomBlock->getInstList().insert(DomBlock->getTerminator(), I);
Bill Wendlingb7427032006-11-26 09:46:52 +0000250 DOUT << "Hoisted: " << *I;
Chris Lattnerc3e903f2004-10-06 03:27:37 +0000251 }
252 }
253 }
254 }
255
Chris Lattner24ad00d2004-03-16 23:29:09 +0000256 // Tail duplication can not update SSA properties correctly if the values
257 // defined in the duplicated tail are used outside of the tail itself. For
258 // this reason, we spill all values that are used outside of the tail to the
259 // stack.
260 for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
261 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
262 ++UI) {
263 bool ShouldDemote = false;
264 if (cast<Instruction>(*UI)->getParent() != DestBlock) {
265 // We must allow our successors to use tail values in their PHI nodes
266 // (if the incoming value corresponds to the tail block).
267 if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
268 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
269 if (PN->getIncomingValue(i) == I &&
270 PN->getIncomingBlock(i) != DestBlock) {
271 ShouldDemote = true;
272 break;
273 }
274
275 } else {
276 ShouldDemote = true;
277 }
278 } else if (PHINode *PN = dyn_cast<PHINode>(cast<Instruction>(*UI))) {
279 // If the user of this instruction is a PHI node in the current block,
Chris Lattner50eafbc2004-03-16 23:36:49 +0000280 // which has an entry from another block using the value, spill it.
281 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
282 if (PN->getIncomingValue(i) == I &&
283 PN->getIncomingBlock(i) != DestBlock) {
284 ShouldDemote = true;
285 break;
286 }
Chris Lattner24ad00d2004-03-16 23:29:09 +0000287 }
288
289 if (ShouldDemote) {
290 // We found a use outside of the tail. Create a new stack slot to
291 // break this inter-block usage pattern.
292 DemoteRegToStack(*I);
293 break;
294 }
295 }
296
Chris Lattner7a7bef42003-06-22 20:10:28 +0000297 // We are going to have to map operands from the original block B to the new
298 // copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
299 // nodes also define part of this mapping. Loop over these PHI nodes, adding
300 // them to our mapping.
Chris Lattnerea635cd2003-06-22 20:25:27 +0000301 //
Chris Lattner7a7bef42003-06-22 20:10:28 +0000302 std::map<Value*, Value*> ValueMapping;
303
304 BasicBlock::iterator BI = DestBlock->begin();
305 bool HadPHINodes = isa<PHINode>(BI);
306 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
307 ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
308
309 // Clone the non-phi instructions of the dest block into the source block,
310 // keeping track of the mapping...
311 //
312 for (; BI != DestBlock->end(); ++BI) {
313 Instruction *New = BI->clone();
314 New->setName(BI->getName());
315 SourceBlock->getInstList().push_back(New);
316 ValueMapping[BI] = New;
317 }
318
319 // Now that we have built the mapping information and cloned all of the
320 // instructions (giving us a new terminator, among other things), walk the new
321 // instructions, rewriting references of old instructions to use new
322 // instructions.
323 //
324 BI = Branch; ++BI; // Get an iterator to the first new instruction
325 for (; BI != SourceBlock->end(); ++BI)
326 for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
327 if (Value *Remapped = ValueMapping[BI->getOperand(i)])
328 BI->setOperand(i, Remapped);
329
330 // Next we check to see if any of the successors of DestBlock had PHI nodes.
331 // If so, we need to add entries to the PHI nodes for SourceBlock now.
332 for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
333 SI != SE; ++SI) {
334 BasicBlock *Succ = *SI;
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000335 for (BasicBlock::iterator PNI = Succ->begin(); isa<PHINode>(PNI); ++PNI) {
336 PHINode *PN = cast<PHINode>(PNI);
Chris Lattner7a7bef42003-06-22 20:10:28 +0000337 // Ok, we have a PHI node. Figure out what the incoming value was for the
338 // DestBlock.
339 Value *IV = PN->getIncomingValueForBlock(DestBlock);
Misha Brukmanfd939082005-04-21 23:48:37 +0000340
Chris Lattner7a7bef42003-06-22 20:10:28 +0000341 // Remap the value if necessary...
342 if (Value *MappedIV = ValueMapping[IV])
343 IV = MappedIV;
344 PN->addIncoming(IV, SourceBlock);
345 }
346 }
Chris Lattner24ad00d2004-03-16 23:29:09 +0000347
348 // Next, remove the old branch instruction, and any PHI node entries that we
349 // had.
350 BI = Branch; ++BI; // Get an iterator to the first new instruction
351 DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
352 SourceBlock->getInstList().erase(Branch); // Destroy the uncond branch...
Chris Lattner7a7bef42003-06-22 20:10:28 +0000353
354 // Final step: now that we have finished everything up, walk the cloned
355 // instructions one last time, constant propagating and DCE'ing them, because
356 // they may not be needed anymore.
357 //
Chris Lattner7a7bef42003-06-22 20:10:28 +0000358 if (HadPHINodes)
359 while (BI != SourceBlock->end())
360 if (!dceInstruction(BI) && !doConstantPropagation(BI))
361 ++BI;
362
Chris Lattner7a7bef42003-06-22 20:10:28 +0000363 ++NumEliminated; // We just killed a branch!
364}