blob: 2a5a606282125e33579ec8514a6b93a7216c81dc [file] [log] [blame]
Chris Lattnera5434ca2003-06-22 20:10:28 +00001//===- TailDuplication.cpp - Simplify CFG through tail duplication --------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// 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.
7//
8//===----------------------------------------------------------------------===//
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 Lattnera5434ca2003-06-22 20:10:28 +000025#include "llvm/Pass.h"
26#include "llvm/Type.h"
27#include "llvm/Support/CFG.h"
28#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerc14da962004-04-18 00:52:43 +000029#include "Support/CommandLine.h"
Chris Lattner8abcd562003-08-01 22:15:03 +000030#include "Support/Debug.h"
Chris Lattnera5434ca2003-06-22 20:10:28 +000031#include "Support/Statistic.h"
Chris Lattner49525f82004-01-09 06:02:20 +000032using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000033
Chris Lattnera5434ca2003-06-22 20:10:28 +000034namespace {
Chris Lattnerc14da962004-04-18 00:52:43 +000035 cl::opt<unsigned>
36 Threshold("taildup-threshold", cl::desc("Max block size to tail duplicate"),
37 cl::init(6), cl::Hidden);
Chris Lattnera5434ca2003-06-22 20:10:28 +000038 Statistic<> NumEliminated("tailduplicate",
39 "Number of unconditional branches eliminated");
40 Statistic<> NumPHINodes("tailduplicate", "Number of phi nodes inserted");
41
42 class TailDup : public FunctionPass {
43 bool runOnFunction(Function &F);
44 private:
45 inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
46 inline void eliminateUnconditionalBranch(BranchInst *BI);
Chris Lattnera5434ca2003-06-22 20:10:28 +000047 };
48 RegisterOpt<TailDup> X("tailduplicate", "Tail Duplication");
49}
50
Brian Gaeke960707c2003-11-11 22:41:34 +000051// Public interface to the Tail Duplication pass
Chris Lattner49525f82004-01-09 06:02:20 +000052Pass *llvm::createTailDuplicationPass() { return new TailDup(); }
Chris Lattnera5434ca2003-06-22 20:10:28 +000053
54/// runOnFunction - Top level algorithm - Loop over each unconditional branch in
55/// the function, eliminating it if it looks attractive enough.
56///
57bool TailDup::runOnFunction(Function &F) {
58 bool Changed = false;
59 for (Function::iterator I = F.begin(), E = F.end(); I != E; )
Chris Lattner95057f62004-03-16 23:29:09 +000060 if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
Chris Lattnera5434ca2003-06-22 20:10:28 +000061 eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
62 Changed = true;
63 } else {
64 ++I;
65 }
66 return Changed;
67}
68
69/// shouldEliminateUnconditionalBranch - Return true if this branch looks
70/// attractive to eliminate. We eliminate the branch if the destination basic
71/// block has <= 5 instructions in it, not counting PHI nodes. In practice,
72/// since one of these is a terminator instruction, this means that we will add
73/// up to 4 instructions to the new block.
74///
75/// We don't count PHI nodes in the count since they will be removed when the
76/// contents of the block are copied over.
77///
78bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
79 BranchInst *BI = dyn_cast<BranchInst>(TI);
80 if (!BI || !BI->isUnconditional()) return false; // Not an uncond branch!
81
82 BasicBlock *Dest = BI->getSuccessor(0);
83 if (Dest == BI->getParent()) return false; // Do not loop infinitely!
84
Chris Lattnerd78ebd02003-07-23 03:32:41 +000085 // Do not inline a block if we will just get another branch to the same block!
Chris Lattnera64923a2004-03-16 19:45:22 +000086 TerminatorInst *DTI = Dest->getTerminator();
87 if (BranchInst *DBI = dyn_cast<BranchInst>(DTI))
Chris Lattnerd78ebd02003-07-23 03:32:41 +000088 if (DBI->isUnconditional() && DBI->getSuccessor(0) == Dest)
89 return false; // Do not loop infinitely!
90
Chris Lattner95057f62004-03-16 23:29:09 +000091 // FIXME: DemoteRegToStack cannot yet demote invoke instructions to the stack,
92 // because doing so would require breaking critical edges. This should be
93 // fixed eventually.
94 if (!DTI->use_empty())
95 return false;
96
Chris Lattnera5434ca2003-06-22 20:10:28 +000097 // Do not bother working on dead blocks...
98 pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
99 if (PI == PE && Dest != Dest->getParent()->begin())
100 return false; // It's just a dead block, ignore it...
101
102 // Also, do not bother with blocks with only a single predecessor: simplify
103 // CFG will fold these two blocks together!
104 ++PI;
105 if (PI == PE) return false; // Exactly one predecessor!
106
107 BasicBlock::iterator I = Dest->begin();
108 while (isa<PHINode>(*I)) ++I;
109
110 for (unsigned Size = 0; I != Dest->end(); ++Size, ++I)
Chris Lattnerc14da962004-04-18 00:52:43 +0000111 if (Size == Threshold) return false; // The block is too large...
Chris Lattnera64923a2004-03-16 19:45:22 +0000112
113 // Do not tail duplicate a block that has thousands of successors into a block
114 // with a single successor if the block has many other predecessors. This can
115 // cause an N^2 explosion in CFG edges (and PHI node entries), as seen in
116 // cases that have a large number of indirect gotos.
117 if (DTI->getNumSuccessors() > 8)
118 if (std::distance(PI, PE) * DTI->getNumSuccessors() > 128)
119 return false;
120
Chris Lattnera5434ca2003-06-22 20:10:28 +0000121 return true;
122}
123
124
125/// eliminateUnconditionalBranch - Clone the instructions from the destination
126/// block into the source block, eliminating the specified unconditional branch.
127/// If the destination block defines values used by successors of the dest
128/// block, we may need to insert PHI nodes.
129///
130void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
131 BasicBlock *SourceBlock = Branch->getParent();
132 BasicBlock *DestBlock = Branch->getSuccessor(0);
133 assert(SourceBlock != DestBlock && "Our predicate is broken!");
134
135 DEBUG(std::cerr << "TailDuplication[" << SourceBlock->getParent()->getName()
136 << "]: Eliminating branch: " << *Branch);
137
Chris Lattner95057f62004-03-16 23:29:09 +0000138 // Tail duplication can not update SSA properties correctly if the values
139 // defined in the duplicated tail are used outside of the tail itself. For
140 // this reason, we spill all values that are used outside of the tail to the
141 // stack.
142 for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
143 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
144 ++UI) {
145 bool ShouldDemote = false;
146 if (cast<Instruction>(*UI)->getParent() != DestBlock) {
147 // We must allow our successors to use tail values in their PHI nodes
148 // (if the incoming value corresponds to the tail block).
149 if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
150 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
151 if (PN->getIncomingValue(i) == I &&
152 PN->getIncomingBlock(i) != DestBlock) {
153 ShouldDemote = true;
154 break;
155 }
156
157 } else {
158 ShouldDemote = true;
159 }
160 } else if (PHINode *PN = dyn_cast<PHINode>(cast<Instruction>(*UI))) {
161 // If the user of this instruction is a PHI node in the current block,
Chris Lattnera3783a52004-03-16 23:36:49 +0000162 // which has an entry from another block using the value, spill it.
163 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
164 if (PN->getIncomingValue(i) == I &&
165 PN->getIncomingBlock(i) != DestBlock) {
166 ShouldDemote = true;
167 break;
168 }
Chris Lattner95057f62004-03-16 23:29:09 +0000169 }
170
171 if (ShouldDemote) {
172 // We found a use outside of the tail. Create a new stack slot to
173 // break this inter-block usage pattern.
174 DemoteRegToStack(*I);
175 break;
176 }
177 }
178
Chris Lattnera5434ca2003-06-22 20:10:28 +0000179 // We are going to have to map operands from the original block B to the new
180 // copy of the block B'. If there are PHI nodes in the DestBlock, these PHI
181 // nodes also define part of this mapping. Loop over these PHI nodes, adding
182 // them to our mapping.
Chris Lattner268c1392003-06-22 20:25:27 +0000183 //
Chris Lattnera5434ca2003-06-22 20:10:28 +0000184 std::map<Value*, Value*> ValueMapping;
185
186 BasicBlock::iterator BI = DestBlock->begin();
187 bool HadPHINodes = isa<PHINode>(BI);
188 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
189 ValueMapping[PN] = PN->getIncomingValueForBlock(SourceBlock);
190
191 // Clone the non-phi instructions of the dest block into the source block,
192 // keeping track of the mapping...
193 //
194 for (; BI != DestBlock->end(); ++BI) {
195 Instruction *New = BI->clone();
196 New->setName(BI->getName());
197 SourceBlock->getInstList().push_back(New);
198 ValueMapping[BI] = New;
199 }
200
201 // Now that we have built the mapping information and cloned all of the
202 // instructions (giving us a new terminator, among other things), walk the new
203 // instructions, rewriting references of old instructions to use new
204 // instructions.
205 //
206 BI = Branch; ++BI; // Get an iterator to the first new instruction
207 for (; BI != SourceBlock->end(); ++BI)
208 for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
209 if (Value *Remapped = ValueMapping[BI->getOperand(i)])
210 BI->setOperand(i, Remapped);
211
212 // Next we check to see if any of the successors of DestBlock had PHI nodes.
213 // If so, we need to add entries to the PHI nodes for SourceBlock now.
214 for (succ_iterator SI = succ_begin(DestBlock), SE = succ_end(DestBlock);
215 SI != SE; ++SI) {
216 BasicBlock *Succ = *SI;
217 for (BasicBlock::iterator PNI = Succ->begin();
218 PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
219 // Ok, we have a PHI node. Figure out what the incoming value was for the
220 // DestBlock.
221 Value *IV = PN->getIncomingValueForBlock(DestBlock);
222
223 // Remap the value if necessary...
224 if (Value *MappedIV = ValueMapping[IV])
225 IV = MappedIV;
226 PN->addIncoming(IV, SourceBlock);
227 }
228 }
Chris Lattner95057f62004-03-16 23:29:09 +0000229
230 // Next, remove the old branch instruction, and any PHI node entries that we
231 // had.
232 BI = Branch; ++BI; // Get an iterator to the first new instruction
233 DestBlock->removePredecessor(SourceBlock); // Remove entries in PHI nodes...
234 SourceBlock->getInstList().erase(Branch); // Destroy the uncond branch...
Chris Lattnera5434ca2003-06-22 20:10:28 +0000235
236 // Final step: now that we have finished everything up, walk the cloned
237 // instructions one last time, constant propagating and DCE'ing them, because
238 // they may not be needed anymore.
239 //
Chris Lattnera5434ca2003-06-22 20:10:28 +0000240 if (HadPHINodes)
241 while (BI != SourceBlock->end())
242 if (!dceInstruction(BI) && !doConstantPropagation(BI))
243 ++BI;
244
Chris Lattnera5434ca2003-06-22 20:10:28 +0000245 ++NumEliminated; // We just killed a branch!
246}