Split into two passes. Now there is the general loop extractor, usable on
[oota-llvm.git] / lib / Transforms / IPO / LoopExtractor.cpp
1 //===- LoopExtractor.cpp - Extract each loop into a new function ----------===//
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 // A pass wrapper around the ExtractLoop() scalar transformation to extract each
11 // top-level loop into its own new function. If the loop is the ONLY loop in a
12 // given function, it is not touched. This is a pass most useful for debugging
13 // via bugpoint.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Transforms/IPO.h"
18 #include "llvm/Module.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/Transforms/Utils/FunctionUtils.h"
23 using namespace llvm;
24
25 namespace {
26   // FIXME: This is not a function pass, but the PassManager doesn't allow
27   // Module passes to require FunctionPasses, so we can't get loop info if we're
28   // not a function pass.
29   struct LoopExtractor : public FunctionPass {
30     unsigned NumLoops;
31
32     LoopExtractor(unsigned numLoops = ~0) : NumLoops(numLoops) {}
33
34     virtual bool runOnFunction(Function &F);
35     
36     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
37       AU.addRequired<LoopInfo>();
38       AU.addRequiredID(LoopSimplifyID);
39     }
40   };
41
42   RegisterOpt<LoopExtractor> 
43   X("loop-extract", "Extract loops into new functions");
44
45   /// SingleLoopExtractor - For bugpoint.
46   struct SingleLoopExtractor : public LoopExtractor {
47     SingleLoopExtractor() : LoopExtractor(1) {}
48   };
49
50   RegisterOpt<SingleLoopExtractor> 
51   Y("loop-extract-single", "Extract at most one loop into a new function");
52 } // End anonymous namespace 
53
54 bool LoopExtractor::runOnFunction(Function &F) {
55   LoopInfo &LI = getAnalysis<LoopInfo>();
56
57   // We don't want to keep extracting the only loop of a function into a new one
58   if (LI.begin() == LI.end() || LI.begin() + 1 == LI.end())
59     return false;
60
61   bool Changed = false;
62
63   // Try to move each loop out of the code into separate function
64   for (LoopInfo::iterator i = LI.begin(), e = LI.end(); i != e; ++i) {
65     if (NumLoops == 0) return Changed;
66     --NumLoops;
67     Changed |= (ExtractLoop(*i) != 0);
68   }
69
70   return Changed;
71 }
72
73 // createSingleLoopExtractorPass - This pass extracts one natural loop from the
74 // program into a function if it can.  This is used by bugpoint.
75 //
76 Pass *llvm::createSingleLoopExtractorPass() {
77   return new SingleLoopExtractor();
78 }