Make the threshold a parameter
[oota-llvm.git] / lib / Transforms / Scalar / LoopUnswitch.cpp
1 //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
2 //
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 //===----------------------------------------------------------------------===//
9 //
10 // This pass transforms loops that contain branches on loop-invariant conditions
11 // to have multiple loops.  For example, it turns the left into the right code:
12 //
13 //  for (...)                  if (lic)
14 //    A                          for (...)
15 //    if (lic)                     A; B; C
16 //      B                      else
17 //    C                          for (...)
18 //                                 A; C
19 //
20 // This can increase the size of the code exponentially (doubling it every time
21 // a loop is unswitched) so we only unswitch if the resultant code will be
22 // smaller than a threshold.
23 //
24 // This pass expects LICM to be run before it to hoist invariant conditions out
25 // of the loop, to make the unswitching opportunity obvious.
26 //
27 //===----------------------------------------------------------------------===//
28
29 #define DEBUG_TYPE "loop-unswitch"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Constants.h"
32 #include "llvm/Function.h"
33 #include "llvm/Instructions.h"
34 #include "llvm/Analysis/LoopInfo.h"
35 #include "llvm/Transforms/Utils/Cloning.h"
36 #include "llvm/Transforms/Utils/Local.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/CommandLine.h"
40 #include <algorithm>
41 #include <iostream>
42 #include <set>
43 using namespace llvm;
44
45 namespace {
46   Statistic<> NumUnswitched("loop-unswitch", "Number of loops unswitched");
47   cl::opt<unsigned>
48   Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
49             cl::init(10), cl::Hidden);
50   
51   class LoopUnswitch : public FunctionPass {
52     LoopInfo *LI;  // Loop information
53   public:
54     virtual bool runOnFunction(Function &F);
55     bool visitLoop(Loop *L);
56
57     /// This transformation requires natural loop information & requires that
58     /// loop preheaders be inserted into the CFG...
59     ///
60     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
61       AU.addRequiredID(LoopSimplifyID);
62       AU.addRequired<LoopInfo>();
63       AU.addPreserved<LoopInfo>();
64     }
65
66   private:
67     void VersionLoop(Value *LIC, Loop *L);
68     BasicBlock *SplitBlock(BasicBlock *BB, bool SplitAtTop);
69     void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC, bool Val);
70   };
71   RegisterOpt<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
72 }
73
74 FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }
75
76 bool LoopUnswitch::runOnFunction(Function &F) {
77   bool Changed = false;
78   LI = &getAnalysis<LoopInfo>();
79
80   // Transform all the top-level loops.  Copy the loop list so that the child
81   // can update the loop tree if it needs to delete the loop.
82   std::vector<Loop*> SubLoops(LI->begin(), LI->end());
83   for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
84     Changed |= visitLoop(SubLoops[i]);
85
86   return Changed;
87 }
88
89
90 /// InsertPHINodesForUsesOutsideLoop - If this instruction is used outside of
91 /// the specified loop, insert a PHI node in the appropriate exit block to merge
92 /// the values in the two different loop versions.
93 ///
94 /// Most values are not used outside of the loop they are defined in, so be
95 /// efficient for this case.
96 ///
97 static bool LoopValuesUsedOutsideLoop(Loop *L) {
98   // We will be doing lots of "loop contains block" queries.  Loop::contains is
99   // linear time, use a set to speed this up.
100   std::set<BasicBlock*> LoopBlocks;
101
102   for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
103        BB != E; ++BB)
104     LoopBlocks.insert(*BB);
105   
106   for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
107        BB != E; ++BB) {
108     for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
109       for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
110            ++UI) {
111         BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
112         if (!LoopBlocks.count(UserBB))
113           return true;
114       }
115   }
116   return false;
117 }
118
119 bool LoopUnswitch::visitLoop(Loop *L) {
120   bool Changed = false;
121
122   // Recurse through all subloops before we process this loop.  Copy the loop
123   // list so that the child can update the loop tree if it needs to delete the
124   // loop.
125   std::vector<Loop*> SubLoops(L->begin(), L->end());
126   for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
127     Changed |= visitLoop(SubLoops[i]);
128
129   // Loop over all of the basic blocks in the loop.  If we find an interior
130   // block that is branching on a loop-invariant condition, we can unswitch this
131   // loop.
132   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
133        I != E; ++I) {
134     TerminatorInst *TI = (*I)->getTerminator();
135     if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
136       if (!isa<Constant>(SI) && L->isLoopInvariant(SI->getCondition()))
137         DEBUG(std::cerr << "TODO: Implement unswitching 'switch' loop %"
138               << L->getHeader()->getName() << ", cost = "
139               << L->getBlocks().size() << "\n" << **I);
140       continue;
141     }
142     
143     BranchInst *BI = dyn_cast<BranchInst>(TI);
144     if (!BI) continue;
145     
146     // If this isn't branching on an invariant condition, we can't unswitch it.
147     if (!BI->isConditional() || isa<Constant>(BI->getCondition()) ||
148         !L->isLoopInvariant(BI->getCondition()))
149       continue;
150     
151     // Check to see if it would be profitable to unswitch this loop.
152     if (L->getBlocks().size() > Threshold) {
153       // FIXME: this should estimate growth by the amount of code shared by the
154       // resultant unswitched loops.  This should have no code growth:
155       //    for () { if (iv) {...} }
156       // as one copy of the loop will be empty.
157       //
158       DEBUG(std::cerr << "NOT unswitching loop %"
159             << L->getHeader()->getName() << ", cost too high: "
160             << L->getBlocks().size() << "\n");
161       continue;
162     }
163     
164     // If this loop has live-out values, we can't unswitch it. We need something
165     // like loop-closed SSA form in order to know how to insert PHI nodes for
166     // these values.
167     if (LoopValuesUsedOutsideLoop(L)) {
168       DEBUG(std::cerr << "NOT unswitching loop %"
169                       << L->getHeader()->getName()
170                       << ", a loop value is used outside loop!\n");
171       continue;
172     }
173       
174     //std::cerr << "BEFORE:\n"; LI->dump();
175     VersionLoop(BI->getCondition(), L);
176     //std::cerr << "AFTER:\n"; LI->dump();
177     
178     // FIXME: Why return here?  What if we have:
179     // "for () { if (iv1) { if (iv2) { } } }" ?
180     return true;
181   }
182
183   return Changed;
184 }
185
186 /// SplitBlock - Split the specified basic block into two pieces.  If SplitAtTop
187 /// is false, this splits the block so the second half only has an unconditional
188 /// branch.  If SplitAtTop is true, it makes it so the first half of the block
189 /// only has an unconditional branch in it.
190 ///
191 /// This method updates the LoopInfo for this function to correctly reflect the
192 /// CFG changes made.
193 BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *BB, bool SplitAtTop) {
194   BasicBlock::iterator SplitPoint;
195   if (!SplitAtTop)
196     SplitPoint = BB->getTerminator();
197   else {
198     SplitPoint = BB->begin();
199     while (isa<PHINode>(SplitPoint)) ++SplitPoint;
200   }
201
202   BasicBlock *New = BB->splitBasicBlock(SplitPoint, BB->getName()+".tail");
203   // New now lives in whichever loop that BB used to.
204   if (Loop *L = LI->getLoopFor(BB))
205     L->addBasicBlockToLoop(New, *LI);
206   return SplitAtTop ? BB : New;
207 }
208
209
210 // RemapInstruction - Convert the instruction operands from referencing the
211 // current values into those specified by ValueMap.
212 //
213 static inline void RemapInstruction(Instruction *I,
214                                     std::map<const Value *, Value*> &ValueMap) {
215   for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
216     Value *Op = I->getOperand(op);
217     std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
218     if (It != ValueMap.end()) Op = It->second;
219     I->setOperand(op, Op);
220   }
221 }
222
223 /// CloneLoop - Recursively clone the specified loop and all of its children,
224 /// mapping the blocks with the specified map.
225 static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM,
226                        LoopInfo *LI) {
227   Loop *New = new Loop();
228
229   if (PL)
230     PL->addChildLoop(New);
231   else
232     LI->addTopLevelLoop(New);
233
234   // Add all of the blocks in L to the new loop.
235   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
236        I != E; ++I)
237     if (LI->getLoopFor(*I) == L)
238       New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
239
240   // Add all of the subloops to the new loop.
241   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
242     CloneLoop(*I, New, VM, LI);
243
244   return New;
245 }
246
247
248 /// VersionLoop - We determined that the loop is profitable to unswitch and
249 /// contains a branch on a loop invariant condition.  Split it into loop
250 /// versions and test the condition outside of either loop.
251 void LoopUnswitch::VersionLoop(Value *LIC, Loop *L) {
252   Function *F = L->getHeader()->getParent();
253
254   DEBUG(std::cerr << "loop-unswitch: Unswitching loop %"
255         << L->getHeader()->getName() << " [" << L->getBlocks().size()
256         << " blocks] in Function " << F->getName()
257         << " on cond:" << *LIC << "\n");
258
259   std::vector<BasicBlock*> LoopBlocks;
260
261   // First step, split the preheader and exit blocks, and add these blocks to
262   // the LoopBlocks list.
263   BasicBlock *OrigPreheader = L->getLoopPreheader();
264   LoopBlocks.push_back(SplitBlock(OrigPreheader, false));
265
266   // We want the loop to come after the preheader, but before the exit blocks.
267   LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
268
269   std::vector<BasicBlock*> ExitBlocks;
270   L->getExitBlocks(ExitBlocks);
271   std::sort(ExitBlocks.begin(), ExitBlocks.end());
272   ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
273                    ExitBlocks.end());
274   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
275     LoopBlocks.push_back(ExitBlocks[i] = SplitBlock(ExitBlocks[i], true));
276
277   // Next step, clone all of the basic blocks that make up the loop (including
278   // the loop preheader and exit blocks), keeping track of the mapping between
279   // the instructions and blocks.
280   std::vector<BasicBlock*> NewBlocks;
281   NewBlocks.reserve(LoopBlocks.size());
282   std::map<const Value*, Value*> ValueMap;
283   for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
284     NewBlocks.push_back(CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F));
285     ValueMap[LoopBlocks[i]] = NewBlocks.back();  // Keep the BB mapping.
286   }
287
288   // Splice the newly inserted blocks into the function right before the
289   // original preheader.
290   F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
291                                 NewBlocks[0], F->end());
292
293   // Now we create the new Loop object for the versioned loop.
294   Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);
295   if (Loop *Parent = L->getParentLoop()) {
296     // Make sure to add the cloned preheader and exit blocks to the parent loop
297     // as well.
298     Parent->addBasicBlockToLoop(NewBlocks[0], *LI);
299     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
300       Parent->addBasicBlockToLoop(cast<BasicBlock>(ValueMap[ExitBlocks[i]]),
301                                   *LI);
302   }
303
304   // Rewrite the code to refer to itself.
305   for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
306     for (BasicBlock::iterator I = NewBlocks[i]->begin(),
307            E = NewBlocks[i]->end(); I != E; ++I)
308       RemapInstruction(I, ValueMap);
309   
310   // Rewrite the original preheader to select between versions of the loop.
311   assert(isa<BranchInst>(OrigPreheader->getTerminator()) &&
312          cast<BranchInst>(OrigPreheader->getTerminator())->isUnconditional() &&
313          OrigPreheader->getTerminator()->getSuccessor(0) == LoopBlocks[0] &&
314          "Preheader splitting did not work correctly!");
315   // Remove the unconditional branch to LoopBlocks[0].
316   OrigPreheader->getInstList().pop_back();
317
318   // Insert a conditional branch on LIC to the two preheaders.  The original
319   // code is the true version and the new code is the false version.
320   new BranchInst(LoopBlocks[0], NewBlocks[0], LIC, OrigPreheader);
321
322   // Now we rewrite the original code to know that the condition is true and the
323   // new code to know that the condition is false.
324   RewriteLoopBodyWithConditionConstant(L, LIC, true);
325   RewriteLoopBodyWithConditionConstant(NewLoop, LIC, false);
326   ++NumUnswitched;
327
328   // Try to unswitch each of our new loops now!
329   visitLoop(L);
330   visitLoop(NewLoop);
331 }
332
333 // RewriteLoopBodyWithConditionConstant - We know that the boolean value LIC has
334 // the value specified by Val in the specified loop.  Rewrite any uses of LIC or
335 // of properties correlated to it.
336 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
337                                                         bool Val) {
338   // FIXME: Support correlated properties, like:
339   //  for (...)
340   //    if (li1 < li2)
341   //      ...
342   //    if (li1 > li2)
343   //      ...
344   ConstantBool *BoolVal = ConstantBool::get(Val);
345
346   std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
347   for (unsigned i = 0, e = Users.size(); i != e; ++i)
348     if (Instruction *U = dyn_cast<Instruction>(Users[i]))
349       if (L->contains(U->getParent()))
350         U->replaceUsesOfWith(LIC, BoolVal);
351 }