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