blob: c0b7e7944f863dcdf1fbbb11bf85837dd8cc6f2a [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//
Chris Lattner4ee451d2007-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 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:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000046 static char ID; // Pass identification, 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.
Chris Lattner0647ebf2007-11-04 06:37:55 +0000118
119 // Don't tail duplicate call instructions. They are very large compared to
120 // other instructions.
121 if (isa<CallInst>(I) || isa<InvokeInst>(I)) return false;
122
Chris Lattnerb9df9b42004-11-22 17:23:57 +0000123 // Only count instructions that are not debugger intrinsics.
124 if (!isa<DbgInfoIntrinsic>(I)) ++Size;
125 }
Chris Lattner4bebf082004-03-16 19:45:22 +0000126
127 // Do not tail duplicate a block that has thousands of successors into a block
128 // with a single successor if the block has many other predecessors. This can
129 // cause an N^2 explosion in CFG edges (and PHI node entries), as seen in
130 // cases that have a large number of indirect gotos.
Chris Lattner7e54a012004-11-01 07:05:07 +0000131 unsigned NumSuccs = DTI->getNumSuccessors();
132 if (NumSuccs > 8) {
133 unsigned TooMany = 128;
134 if (NumSuccs >= TooMany) return false;
135 TooMany = TooMany/NumSuccs;
136 for (; PI != PE; ++PI)
137 if (TooMany-- == 0) return false;
138 }
Chris Lattnere99c6232006-09-07 21:30:15 +0000139
140 // Finally, if this unconditional branch is a fall-through, be careful about
141 // tail duplicating it. In particular, we don't want to taildup it if the
142 // original block will still be there after taildup is completed: doing so
143 // would eliminate the fall-through, requiring unconditional branches.
144 Function::iterator DestI = Dest;
145 if (&*--DestI == BI->getParent()) {
146 // The uncond branch is a fall-through. Tail duplication of the block is
147 // will eliminate the fall-through-ness and end up cloning the terminator
148 // at the end of the Dest block. Since the original Dest block will
149 // continue to exist, this means that one or the other will not be able to
150 // fall through. One typical example that this helps with is code like:
151 // if (a)
152 // foo();
153 // if (b)
154 // foo();
155 // Cloning the 'if b' block into the end of the first foo block is messy.
Chris Lattnerdfa1af02006-09-10 18:17:58 +0000156
157 // The messy case is when the fall-through block falls through to other
158 // blocks. This is what we would be preventing if we cloned the block.
159 DestI = Dest;
160 if (++DestI != Dest->getParent()->end()) {
161 BasicBlock *DestSucc = DestI;
162 // If any of Dest's successors are fall-throughs, don't do this xform.
163 for (succ_iterator SI = succ_begin(Dest), SE = succ_end(Dest);
164 SI != SE; ++SI)
165 if (*SI == DestSucc)
166 return false;
167 }
Chris Lattnere99c6232006-09-07 21:30:15 +0000168 }
Chris Lattner4bebf082004-03-16 19:45:22 +0000169
Misha Brukmanfd939082005-04-21 23:48:37 +0000170 return true;
Chris Lattner7a7bef42003-06-22 20:10:28 +0000171}
172
Chris Lattnerc3e903f2004-10-06 03:27:37 +0000173/// FindObviousSharedDomOf - We know there is a branch from SrcBlock to
174/// DestBlock, and that SrcBlock is not the only predecessor of DstBlock. If we
175/// can find a predecessor of SrcBlock that is a dominator of both SrcBlock and
176/// DstBlock, return it.
177static BasicBlock *FindObviousSharedDomOf(BasicBlock *SrcBlock,
178 BasicBlock *DstBlock) {
179 // SrcBlock must have a single predecessor.
180 pred_iterator PI = pred_begin(SrcBlock), PE = pred_end(SrcBlock);
181 if (PI == PE || ++PI != PE) return 0;
182
183 BasicBlock *SrcPred = *pred_begin(SrcBlock);
Misha Brukmanfd939082005-04-21 23:48:37 +0000184
Chris Lattnerc3e903f2004-10-06 03:27:37 +0000185 // Look at the predecessors of DstBlock. One of them will be SrcBlock. If
186 // there is only one other pred, get it, otherwise we can't handle it.
187 PI = pred_begin(DstBlock); PE = pred_end(DstBlock);
188 BasicBlock *DstOtherPred = 0;
189 if (*PI == SrcBlock) {
190 if (++PI == PE) return 0;
191 DstOtherPred = *PI;
192 if (++PI != PE) return 0;
193 } else {
194 DstOtherPred = *PI;
195 if (++PI == PE || *PI != SrcBlock || ++PI != PE) return 0;
196 }
197
198 // We can handle two situations here: "if then" and "if then else" blocks. An
199 // 'if then' situation is just where DstOtherPred == SrcPred.
200 if (DstOtherPred == SrcPred)
201 return SrcPred;
202
203 // Check to see if we have an "if then else" situation, which means that
204 // DstOtherPred will have a single predecessor and it will be SrcPred.
205 PI = pred_begin(DstOtherPred); PE = pred_end(DstOtherPred);
206 if (PI != PE && *PI == SrcPred) {
207 if (++PI != PE) return 0; // Not a single pred.
208 return SrcPred; // Otherwise, it's an "if then" situation. Return the if.
209 }
210
211 // Otherwise, this is something we can't handle.
212 return 0;
213}
214
Chris Lattner7a7bef42003-06-22 20:10:28 +0000215
216/// eliminateUnconditionalBranch - Clone the instructions from the destination
217/// block into the source block, eliminating the specified unconditional branch.
218/// If the destination block defines values used by successors of the dest
219/// block, we may need to insert PHI nodes.
220///
221void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
222 BasicBlock *SourceBlock = Branch->getParent();
223 BasicBlock *DestBlock = Branch->getSuccessor(0);
224 assert(SourceBlock != DestBlock && "Our predicate is broken!");
225
Bill Wendlingb7427032006-11-26 09:46:52 +0000226 DOUT << "TailDuplication[" << SourceBlock->getParent()->getName()
227 << "]: Eliminating branch: " << *Branch;
Chris Lattner7a7bef42003-06-22 20:10:28 +0000228
Chris Lattnerc3e903f2004-10-06 03:27:37 +0000229 // See if we can avoid duplicating code by moving it up to a dominator of both
230 // blocks.
231 if (BasicBlock *DomBlock = FindObviousSharedDomOf(SourceBlock, DestBlock)) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000232 DOUT << "Found shared dominator: " << DomBlock->getName() << "\n";
Chris Lattnerc3e903f2004-10-06 03:27:37 +0000233
234 // If there are non-phi instructions in DestBlock that have no operands
235 // defined in DestBlock, and if the instruction has no side effects, we can
236 // move the instruction to DomBlock instead of duplicating it.
237 BasicBlock::iterator BBI = DestBlock->begin();
238 while (isa<PHINode>(BBI)) ++BBI;
239 while (!isa<TerminatorInst>(BBI)) {
240 Instruction *I = BBI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000241
Chris Lattnerc3e903f2004-10-06 03:27:37 +0000242 bool CanHoist = !I->isTrapping() && !I->mayWriteToMemory();
243 if (CanHoist) {
244 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
245 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(op)))
246 if (OpI->getParent() == DestBlock ||
247 (isa<InvokeInst>(OpI) && OpI->getParent() == DomBlock)) {
248 CanHoist = false;
249 break;
250 }
251 if (CanHoist) {
252 // Remove from DestBlock, move right before the term in DomBlock.
253 DestBlock->getInstList().remove(I);
254 DomBlock->getInstList().insert(DomBlock->getTerminator(), I);
Bill Wendlingb7427032006-11-26 09:46:52 +0000255 DOUT << "Hoisted: " << *I;
Chris Lattnerc3e903f2004-10-06 03:27:37 +0000256 }
257 }
258 }
259 }
260
Chris Lattner24ad00d2004-03-16 23:29:09 +0000261 // Tail duplication can not update SSA properties correctly if the values
262 // defined in the duplicated tail are used outside of the tail itself. For
263 // this reason, we spill all values that are used outside of the tail to the
264 // stack.
265 for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
266 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
267 ++UI) {
268 bool ShouldDemote = false;
269 if (cast<Instruction>(*UI)->getParent() != DestBlock) {
270 // We must allow our successors to use tail values in their PHI nodes
271 // (if the incoming value corresponds to the tail block).
272 if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
273 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
274 if (PN->getIncomingValue(i) == I &&
275 PN->getIncomingBlock(i) != DestBlock) {
276 ShouldDemote = true;
277 break;
278 }
279
280 } else {
281 ShouldDemote = true;
282 }
283 } else if (PHINode *PN = dyn_cast<PHINode>(cast<Instruction>(*UI))) {
284 // If the user of this instruction is a PHI node in the current block,
Chris Lattner50eafbc2004-03-16 23:36:49 +0000285 // which has an entry from another block using the value, spill it.
286 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
287 if (PN->getIncomingValue(i) == I &&
288 PN->getIncomingBlock(i) != DestBlock) {
289 ShouldDemote = true;
290 break;
291 }
Chris Lattner24ad00d2004-03-16 23:29:09 +0000292 }
293
294 if (ShouldDemote) {
295 // We found a use outside of the tail. Create a new stack slot to
296 // break this inter-block usage pattern.
297 DemoteRegToStack(*I);
298 break;
299 }
300 }
301
Chris Lattner7a7bef42003-06-22 20:10:28 +0000302 // We are going to have to map operands from the original block B to the new
303 // copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
304 // nodes also define part of this mapping. Loop over these PHI nodes, adding
305 // them to our mapping.
Chris Lattnerea635cd2003-06-22 20:25:27 +0000306 //
Chris Lattner7a7bef42003-06-22 20:10:28 +0000307 std::map<Value*, Value*> ValueMapping;
308
309 BasicBlock::iterator BI = DestBlock->begin();
310 bool HadPHINodes = isa<PHINode>(BI);
311 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
312 ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
313
314 // Clone the non-phi instructions of the dest block into the source block,
315 // keeping track of the mapping...
316 //
317 for (; BI != DestBlock->end(); ++BI) {
318 Instruction *New = BI->clone();
319 New->setName(BI->getName());
320 SourceBlock->getInstList().push_back(New);
321 ValueMapping[BI] = New;
322 }
323
324 // Now that we have built the mapping information and cloned all of the
325 // instructions (giving us a new terminator, among other things), walk the new
326 // instructions, rewriting references of old instructions to use new
327 // instructions.
328 //
329 BI = Branch; ++BI; // Get an iterator to the first new instruction
330 for (; BI != SourceBlock->end(); ++BI)
331 for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
332 if (Value *Remapped = ValueMapping[BI->getOperand(i)])
333 BI->setOperand(i, Remapped);
334
335 // Next we check to see if any of the successors of DestBlock had PHI nodes.
336 // If so, we need to add entries to the PHI nodes for SourceBlock now.
337 for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
338 SI != SE; ++SI) {
339 BasicBlock *Succ = *SI;
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000340 for (BasicBlock::iterator PNI = Succ->begin(); isa<PHINode>(PNI); ++PNI) {
341 PHINode *PN = cast<PHINode>(PNI);
Chris Lattner7a7bef42003-06-22 20:10:28 +0000342 // Ok, we have a PHI node. Figure out what the incoming value was for the
343 // DestBlock.
344 Value *IV = PN->getIncomingValueForBlock(DestBlock);
Misha Brukmanfd939082005-04-21 23:48:37 +0000345
Chris Lattner7a7bef42003-06-22 20:10:28 +0000346 // Remap the value if necessary...
347 if (Value *MappedIV = ValueMapping[IV])
348 IV = MappedIV;
349 PN->addIncoming(IV, SourceBlock);
350 }
351 }
Chris Lattner24ad00d2004-03-16 23:29:09 +0000352
353 // Next, remove the old branch instruction, and any PHI node entries that we
354 // had.
355 BI = Branch; ++BI; // Get an iterator to the first new instruction
356 DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
357 SourceBlock->getInstList().erase(Branch); // Destroy the uncond branch...
Chris Lattner7a7bef42003-06-22 20:10:28 +0000358
359 // Final step: now that we have finished everything up, walk the cloned
360 // instructions one last time, constant propagating and DCE'ing them, because
361 // they may not be needed anymore.
362 //
Chris Lattner7a7bef42003-06-22 20:10:28 +0000363 if (HadPHINodes)
364 while (BI != SourceBlock->end())
365 if (!dceInstruction(BI) && !doConstantPropagation(BI))
366 ++BI;
367
Chris Lattner7a7bef42003-06-22 20:10:28 +0000368 ++NumEliminated; // We just killed a branch!
369}