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