blob: c037ee960317754e15a36a5e2cf1c292b74f988c [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- TailDuplication.cpp - Simplify CFG through tail duplication --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
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#define DEBUG_TYPE "tailduplicate"
22#include "llvm/Transforms/Scalar.h"
23#include "llvm/Constant.h"
24#include "llvm/Function.h"
25#include "llvm/Instructions.h"
26#include "llvm/IntrinsicInst.h"
27#include "llvm/Pass.h"
28#include "llvm/Type.h"
29#include "llvm/Support/CFG.h"
Chris Lattner60042bd2008-11-27 22:56:14 +000030#include "llvm/Analysis/ConstantFolding.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000031#include "llvm/Transforms/Utils/Local.h"
32#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/Compiler.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/ADT/Statistic.h"
Dale Johannesen0ba11562008-05-13 20:06:43 +000036#include "llvm/ADT/SmallPtrSet.h"
Dan Gohman249ddbf2008-03-21 23:51:57 +000037#include <map>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000038using namespace llvm;
39
40STATISTIC(NumEliminated, "Number of unconditional branches eliminated");
41
Dan Gohman089efff2008-05-13 00:00:25 +000042static cl::opt<unsigned>
Evan Cheng2c88b9b2008-05-16 07:55:50 +000043TailDupThreshold("taildup-threshold",
44 cl::desc("Max block size to tail duplicate"),
45 cl::init(1), cl::Hidden);
Dan Gohman089efff2008-05-13 00:00:25 +000046
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048 class VISIBILITY_HIDDEN TailDup : public FunctionPass {
49 bool runOnFunction(Function &F);
50 public:
51 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000052 TailDup() : FunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053
54 private:
Evan Cheng2c88b9b2008-05-16 07:55:50 +000055 inline bool shouldEliminateUnconditionalBranch(TerminatorInst *, unsigned);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000056 inline void eliminateUnconditionalBranch(BranchInst *BI);
Dale Johannesen0ba11562008-05-13 20:06:43 +000057 SmallPtrSet<BasicBlock*, 4> CycleDetector;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000058 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059}
60
Dan Gohman089efff2008-05-13 00:00:25 +000061char TailDup::ID = 0;
62static RegisterPass<TailDup> X("tailduplicate", "Tail Duplication");
63
Dan Gohmanf17a25c2007-07-18 16:29:46 +000064// Public interface to the Tail Duplication pass
65FunctionPass *llvm::createTailDuplicationPass() { return new TailDup(); }
66
67/// runOnFunction - Top level algorithm - Loop over each unconditional branch in
Dale Johannesen0ba11562008-05-13 20:06:43 +000068/// the function, eliminating it if it looks attractive enough. CycleDetector
69/// prevents infinite loops by checking that we aren't redirecting a branch to
70/// a place it already pointed to earlier; see PR 2323.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000071bool TailDup::runOnFunction(Function &F) {
72 bool Changed = false;
Dale Johannesen0ba11562008-05-13 20:06:43 +000073 CycleDetector.clear();
74 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
Evan Cheng2c88b9b2008-05-16 07:55:50 +000075 if (shouldEliminateUnconditionalBranch(I->getTerminator(),
76 TailDupThreshold)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000077 eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
78 Changed = true;
79 } else {
80 ++I;
Dale Johannesen0ba11562008-05-13 20:06:43 +000081 CycleDetector.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000082 }
Dale Johannesen0ba11562008-05-13 20:06:43 +000083 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084 return Changed;
85}
86
87/// shouldEliminateUnconditionalBranch - Return true if this branch looks
88/// attractive to eliminate. We eliminate the branch if the destination basic
89/// block has <= 5 instructions in it, not counting PHI nodes. In practice,
90/// since one of these is a terminator instruction, this means that we will add
91/// up to 4 instructions to the new block.
92///
93/// We don't count PHI nodes in the count since they will be removed when the
94/// contents of the block are copied over.
95///
Evan Cheng2c88b9b2008-05-16 07:55:50 +000096bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI,
97 unsigned Threshold) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000098 BranchInst *BI = dyn_cast<BranchInst>(TI);
99 if (!BI || !BI->isUnconditional()) return false; // Not an uncond branch!
100
101 BasicBlock *Dest = BI->getSuccessor(0);
102 if (Dest == BI->getParent()) return false; // Do not loop infinitely!
103
104 // Do not inline a block if we will just get another branch to the same block!
105 TerminatorInst *DTI = Dest->getTerminator();
106 if (BranchInst *DBI = dyn_cast<BranchInst>(DTI))
107 if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
108 return false; // Do not loop infinitely!
109
110 // FIXME: DemoteRegToStack cannot yet demote invoke instructions to the stack,
111 // because doing so would require breaking critical edges. This should be
112 // fixed eventually.
113 if (!DTI->use_empty())
114 return false;
115
Devang Patel4082ea22008-05-15 18:04:29 +0000116 // Do not bother with blocks with only a single predecessor: simplify
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000117 // CFG will fold these two blocks together!
Devang Patel4082ea22008-05-15 18:04:29 +0000118 pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000119 ++PI;
120 if (PI == PE) return false; // Exactly one predecessor!
121
Dan Gohman514277c2008-05-23 21:05:58 +0000122 BasicBlock::iterator I = Dest->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000123
124 for (unsigned Size = 0; I != Dest->end(); ++I) {
125 if (Size == Threshold) return false; // The block is too large.
Chris Lattner5fafff82007-11-04 06:37:55 +0000126
127 // Don't tail duplicate call instructions. They are very large compared to
128 // other instructions.
129 if (isa<CallInst>(I) || isa<InvokeInst>(I)) return false;
Evan Cheng2c88b9b2008-05-16 07:55:50 +0000130
131 // Allso alloca and malloc.
132 if (isa<AllocationInst>(I)) return false;
133
134 // Some vector instructions can expand into a number of instructions.
135 if (isa<ShuffleVectorInst>(I) || isa<ExtractElementInst>(I) ||
136 isa<InsertElementInst>(I)) return false;
Chris Lattner5fafff82007-11-04 06:37:55 +0000137
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000138 // Only count instructions that are not debugger intrinsics.
139 if (!isa<DbgInfoIntrinsic>(I)) ++Size;
140 }
141
142 // Do not tail duplicate a block that has thousands of successors into a block
143 // with a single successor if the block has many other predecessors. This can
144 // cause an N^2 explosion in CFG edges (and PHI node entries), as seen in
145 // cases that have a large number of indirect gotos.
146 unsigned NumSuccs = DTI->getNumSuccessors();
147 if (NumSuccs > 8) {
148 unsigned TooMany = 128;
149 if (NumSuccs >= TooMany) return false;
150 TooMany = TooMany/NumSuccs;
151 for (; PI != PE; ++PI)
152 if (TooMany-- == 0) return false;
153 }
154
Dale Johannesen0ba11562008-05-13 20:06:43 +0000155 // If this unconditional branch is a fall-through, be careful about
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000156 // tail duplicating it. In particular, we don't want to taildup it if the
157 // original block will still be there after taildup is completed: doing so
158 // would eliminate the fall-through, requiring unconditional branches.
159 Function::iterator DestI = Dest;
160 if (&*--DestI == BI->getParent()) {
161 // The uncond branch is a fall-through. Tail duplication of the block is
162 // will eliminate the fall-through-ness and end up cloning the terminator
163 // at the end of the Dest block. Since the original Dest block will
164 // continue to exist, this means that one or the other will not be able to
165 // fall through. One typical example that this helps with is code like:
166 // if (a)
167 // foo();
168 // if (b)
169 // foo();
170 // Cloning the 'if b' block into the end of the first foo block is messy.
171
172 // The messy case is when the fall-through block falls through to other
173 // blocks. This is what we would be preventing if we cloned the block.
174 DestI = Dest;
175 if (++DestI != Dest->getParent()->end()) {
176 BasicBlock *DestSucc = DestI;
177 // If any of Dest's successors are fall-throughs, don't do this xform.
178 for (succ_iterator SI = succ_begin(Dest), SE = succ_end(Dest);
179 SI != SE; ++SI)
180 if (*SI == DestSucc)
181 return false;
182 }
183 }
184
Dale Johannesen0ba11562008-05-13 20:06:43 +0000185 // Finally, check that we haven't redirected to this target block earlier;
186 // there are cases where we loop forever if we don't check this (PR 2323).
187 if (!CycleDetector.insert(Dest))
188 return false;
189
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000190 return true;
191}
192
193/// FindObviousSharedDomOf - We know there is a branch from SrcBlock to
194/// DestBlock, and that SrcBlock is not the only predecessor of DstBlock. If we
195/// can find a predecessor of SrcBlock that is a dominator of both SrcBlock and
196/// DstBlock, return it.
197static BasicBlock *FindObviousSharedDomOf(BasicBlock *SrcBlock,
198 BasicBlock *DstBlock) {
199 // SrcBlock must have a single predecessor.
200 pred_iterator PI = pred_begin(SrcBlock), PE = pred_end(SrcBlock);
201 if (PI == PE || ++PI != PE) return 0;
202
203 BasicBlock *SrcPred = *pred_begin(SrcBlock);
204
205 // Look at the predecessors of DstBlock. One of them will be SrcBlock. If
206 // there is only one other pred, get it, otherwise we can't handle it.
207 PI = pred_begin(DstBlock); PE = pred_end(DstBlock);
208 BasicBlock *DstOtherPred = 0;
209 if (*PI == SrcBlock) {
210 if (++PI == PE) return 0;
211 DstOtherPred = *PI;
212 if (++PI != PE) return 0;
213 } else {
214 DstOtherPred = *PI;
215 if (++PI == PE || *PI != SrcBlock || ++PI != PE) return 0;
216 }
217
218 // We can handle two situations here: "if then" and "if then else" blocks. An
219 // 'if then' situation is just where DstOtherPred == SrcPred.
220 if (DstOtherPred == SrcPred)
221 return SrcPred;
222
223 // Check to see if we have an "if then else" situation, which means that
224 // DstOtherPred will have a single predecessor and it will be SrcPred.
225 PI = pred_begin(DstOtherPred); PE = pred_end(DstOtherPred);
226 if (PI != PE && *PI == SrcPred) {
227 if (++PI != PE) return 0; // Not a single pred.
228 return SrcPred; // Otherwise, it's an "if then" situation. Return the if.
229 }
230
231 // Otherwise, this is something we can't handle.
232 return 0;
233}
234
235
236/// eliminateUnconditionalBranch - Clone the instructions from the destination
237/// block into the source block, eliminating the specified unconditional branch.
238/// If the destination block defines values used by successors of the dest
239/// block, we may need to insert PHI nodes.
240///
241void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
242 BasicBlock *SourceBlock = Branch->getParent();
243 BasicBlock *DestBlock = Branch->getSuccessor(0);
244 assert(SourceBlock != DestBlock && "Our predicate is broken!");
245
246 DOUT << "TailDuplication[" << SourceBlock->getParent()->getName()
247 << "]: Eliminating branch: " << *Branch;
248
249 // See if we can avoid duplicating code by moving it up to a dominator of both
250 // blocks.
251 if (BasicBlock *DomBlock = FindObviousSharedDomOf(SourceBlock, DestBlock)) {
252 DOUT << "Found shared dominator: " << DomBlock->getName() << "\n";
253
254 // If there are non-phi instructions in DestBlock that have no operands
255 // defined in DestBlock, and if the instruction has no side effects, we can
256 // move the instruction to DomBlock instead of duplicating it.
Dan Gohman514277c2008-05-23 21:05:58 +0000257 BasicBlock::iterator BBI = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000258 while (!isa<TerminatorInst>(BBI)) {
259 Instruction *I = BBI++;
260
Duncan Sands2f500832009-05-06 06:49:50 +0000261 bool CanHoist = !I->isTrapping() && !I->mayHaveSideEffects();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262 if (CanHoist) {
263 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
264 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(op)))
265 if (OpI->getParent() == DestBlock ||
266 (isa<InvokeInst>(OpI) && OpI->getParent() == DomBlock)) {
267 CanHoist = false;
268 break;
269 }
270 if (CanHoist) {
271 // Remove from DestBlock, move right before the term in DomBlock.
272 DestBlock->getInstList().remove(I);
273 DomBlock->getInstList().insert(DomBlock->getTerminator(), I);
274 DOUT << "Hoisted: " << *I;
275 }
276 }
277 }
278 }
279
280 // Tail duplication can not update SSA properties correctly if the values
281 // defined in the duplicated tail are used outside of the tail itself. For
282 // this reason, we spill all values that are used outside of the tail to the
283 // stack.
284 for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
Chris Lattnerfe86ab22008-04-20 22:18:22 +0000285 if (I->isUsedOutsideOfBlock(DestBlock)) {
286 // We found a use outside of the tail. Create a new stack slot to
287 // break this inter-block usage pattern.
288 DemoteRegToStack(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000289 }
290
291 // We are going to have to map operands from the original block B to the new
292 // copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
293 // nodes also define part of this mapping. Loop over these PHI nodes, adding
294 // them to our mapping.
295 //
296 std::map<Value*, Value*> ValueMapping;
297
298 BasicBlock::iterator BI = DestBlock->begin();
299 bool HadPHINodes = isa<PHINode>(BI);
300 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
301 ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
302
303 // Clone the non-phi instructions of the dest block into the source block,
304 // keeping track of the mapping...
305 //
306 for (; BI != DestBlock->end(); ++BI) {
307 Instruction *New = BI->clone();
Owen Andersonab567f82008-04-14 17:38:21 +0000308 New->setName(BI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000309 SourceBlock->getInstList().push_back(New);
310 ValueMapping[BI] = New;
311 }
312
313 // Now that we have built the mapping information and cloned all of the
314 // instructions (giving us a new terminator, among other things), walk the new
315 // instructions, rewriting references of old instructions to use new
316 // instructions.
317 //
318 BI = Branch; ++BI; // Get an iterator to the first new instruction
319 for (; BI != SourceBlock->end(); ++BI)
Dan Gohman07c88b02009-07-02 00:17:47 +0000320 for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i) {
321 std::map<Value*, Value*>::const_iterator I =
322 ValueMapping.find(BI->getOperand(i));
323 if (I != ValueMapping.end())
324 BI->setOperand(i, I->second);
325 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000326
327 // Next we check to see if any of the successors of DestBlock had PHI nodes.
328 // If so, we need to add entries to the PHI nodes for SourceBlock now.
329 for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
330 SI != SE; ++SI) {
331 BasicBlock *Succ = *SI;
332 for (BasicBlock::iterator PNI = Succ->begin(); isa<PHINode>(PNI); ++PNI) {
333 PHINode *PN = cast<PHINode>(PNI);
334 // Ok, we have a PHI node. Figure out what the incoming value was for the
335 // DestBlock.
336 Value *IV = PN->getIncomingValueForBlock(DestBlock);
337
338 // Remap the value if necessary...
Dan Gohman07c88b02009-07-02 00:17:47 +0000339 std::map<Value*, Value*>::const_iterator I = ValueMapping.find(IV);
340 if (I != ValueMapping.end())
341 IV = I->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342 PN->addIncoming(IV, SourceBlock);
343 }
344 }
345
346 // Next, remove the old branch instruction, and any PHI node entries that we
347 // had.
348 BI = Branch; ++BI; // Get an iterator to the first new instruction
349 DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
350 SourceBlock->getInstList().erase(Branch); // Destroy the uncond branch...
351
352 // Final step: now that we have finished everything up, walk the cloned
353 // instructions one last time, constant propagating and DCE'ing them, because
354 // they may not be needed anymore.
355 //
Chris Lattner60042bd2008-11-27 22:56:14 +0000356 if (HadPHINodes) {
357 while (BI != SourceBlock->end()) {
358 Instruction *Inst = BI++;
359 if (isInstructionTriviallyDead(Inst))
360 Inst->eraseFromParent();
361 else if (Constant *C = ConstantFoldInstruction(Inst)) {
362 Inst->replaceAllUsesWith(C);
363 Inst->eraseFromParent();
364 }
365 }
366 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000367
368 ++NumEliminated; // We just killed a branch!
369}