add a fixme
[oota-llvm.git] / tools / bugpoint / ExtractFunction.cpp
1 //===- ExtractFunction.cpp - Extract a function from Program --------------===//
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 file implements a method that extracts a function from program, cleans
11 // it up, and returns it as a new module.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "BugDriver.h"
16 #include "llvm/Constant.h"
17 #include "llvm/Module.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Type.h"
21 #include "llvm/Analysis/Verifier.h"
22 #include "llvm/Transforms/IPO.h"
23 #include "llvm/Transforms/Scalar.h"
24 #include "llvm/Transforms/Utils/Cloning.h"
25 #include "llvm/Target/TargetData.h"
26 #include "Support/CommandLine.h"
27 #include "Support/Debug.h"
28 #include "Support/FileUtilities.h"
29 using namespace llvm;
30
31 namespace llvm {
32   bool DisableSimplifyCFG = false;
33 } // End llvm namespace
34
35 namespace {
36   cl::opt<bool>
37   NoDCE ("disable-dce",
38          cl::desc("Do not use the -dce pass to reduce testcases"));
39   cl::opt<bool, true>
40   NoSCFG("disable-simplifycfg", cl::location(DisableSimplifyCFG),
41          cl::desc("Do not use the -simplifycfg pass to reduce testcases"));
42 }
43
44 /// deleteInstructionFromProgram - This method clones the current Program and
45 /// deletes the specified instruction from the cloned module.  It then runs a
46 /// series of cleanup passes (ADCE and SimplifyCFG) to eliminate any code which
47 /// depends on the value.  The modified module is then returned.
48 ///
49 Module *BugDriver::deleteInstructionFromProgram(const Instruction *I,
50                                                 unsigned Simplification) const {
51   Module *Result = CloneModule(Program);
52
53   const BasicBlock *PBB = I->getParent();
54   const Function *PF = PBB->getParent();
55
56   Module::iterator RFI = Result->begin(); // Get iterator to corresponding fn
57   std::advance(RFI, std::distance(PF->getParent()->begin(),
58                                   Module::const_iterator(PF)));
59
60   Function::iterator RBI = RFI->begin();  // Get iterator to corresponding BB
61   std::advance(RBI, std::distance(PF->begin(), Function::const_iterator(PBB)));
62
63   BasicBlock::iterator RI = RBI->begin(); // Get iterator to corresponding inst
64   std::advance(RI, std::distance(PBB->begin(), BasicBlock::const_iterator(I)));
65   Instruction *TheInst = RI;              // Got the corresponding instruction!
66
67   // If this instruction produces a value, replace any users with null values
68   if (TheInst->getType() != Type::VoidTy)
69     TheInst->replaceAllUsesWith(Constant::getNullValue(TheInst->getType()));
70
71   // Remove the instruction from the program.
72   TheInst->getParent()->getInstList().erase(TheInst);
73
74   // Spiff up the output a little bit.
75   PassManager Passes;
76   // Make sure that the appropriate target data is always used...
77   Passes.add(new TargetData("bugpoint", Result));
78
79   if (Simplification > 1 && !NoDCE)
80     Passes.add(createDeadCodeEliminationPass());
81   if (Simplification && !DisableSimplifyCFG)
82     Passes.add(createCFGSimplificationPass());      // Delete dead control flow
83
84   Passes.add(createVerifierPass());
85   Passes.run(*Result);
86   return Result;
87 }
88
89 static const PassInfo *getPI(Pass *P) {
90   const PassInfo *PI = P->getPassInfo();
91   delete P;
92   return PI;
93 }
94
95 /// performFinalCleanups - This method clones the current Program and performs
96 /// a series of cleanups intended to get rid of extra cruft on the module
97 /// before handing it to the user...
98 ///
99 Module *BugDriver::performFinalCleanups(Module *M, bool MayModifySemantics) {
100   // Make all functions external, so GlobalDCE doesn't delete them...
101   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
102     I->setLinkage(GlobalValue::ExternalLinkage);
103   
104   std::vector<const PassInfo*> CleanupPasses;
105   CleanupPasses.push_back(getPI(createFunctionResolvingPass()));
106   CleanupPasses.push_back(getPI(createGlobalDCEPass()));
107   CleanupPasses.push_back(getPI(createDeadTypeEliminationPass()));
108
109   if (MayModifySemantics)
110     CleanupPasses.push_back(getPI(createDeadArgHackingPass()));
111   else
112     CleanupPasses.push_back(getPI(createDeadArgEliminationPass()));
113   
114   std::swap(Program, M);
115   std::string Filename;
116   bool Failed = runPasses(CleanupPasses, Filename);
117   std::swap(Program, M);
118
119   if (Failed) {
120     std::cerr << "Final cleanups failed.  Sorry.  :(\n";
121   } else {
122     delete M;
123     M = ParseInputFile(Filename);
124     if (M == 0) {
125       std::cerr << getToolName() << ": Error reading bytecode file '"
126                 << Filename << "'!\n";
127       exit(1);
128     }
129     removeFile(Filename);
130   }
131   return M;
132 }
133
134
135 // DeleteFunctionBody - "Remove" the function by deleting all of its basic
136 // blocks, making it external.
137 //
138 void llvm::DeleteFunctionBody(Function *F) {
139   // delete the body of the function...
140   F->deleteBody();
141   assert(F->isExternal() && "This didn't make the function external!");
142 }
143
144 /// SplitFunctionsOutOfModule - Given a module and a list of functions in the
145 /// module, split the functions OUT of the specified module, and place them in
146 /// the new module.
147 ///
148 /// FIXME: this could be made DRAMATICALLY more efficient for large programs if
149 /// we just MOVED functions from one module to the other, instead of cloning the
150 /// whole module, then proceeding to delete an entire module's worth of stuff.
151 ///
152 Module *llvm::SplitFunctionsOutOfModule(Module *M,
153                                         const std::vector<Function*> &F) {
154   // Make sure functions & globals are all external so that linkage
155   // between the two modules will work.
156   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
157     I->setLinkage(GlobalValue::ExternalLinkage);
158   for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
159     I->setLinkage(GlobalValue::ExternalLinkage);
160
161   Module *New = CloneModule(M);
162
163   // Make sure global initializers exist only in the safe module (CBE->.so)
164   for (Module::giterator I = New->gbegin(), E = New->gend(); I != E; ++I)
165     I->setInitializer(0);  // Delete the initializer to make it external
166
167   // Remove the Test functions from the Safe module
168   for (unsigned i = 0, e = F.size(); i != e; ++i) {
169     Function *TNOF = M->getFunction(F[i]->getName(), F[i]->getFunctionType());
170     DEBUG(std::cerr << "Removing function " << F[i]->getName() << "\n");
171     assert(TNOF && "Function doesn't exist in module!");
172     DeleteFunctionBody(TNOF);       // Function is now external in this module!
173   }
174
175   // Remove the Safe functions from the Test module
176   for (Module::iterator I = New->begin(), E = New->end(); I != E; ++I) {
177     bool funcFound = false;
178     for (std::vector<Function*>::const_iterator FI = F.begin(), Fe = F.end();
179          FI != Fe; ++FI)
180       if (I->getName() == (*FI)->getName()) funcFound = true;
181
182     if (!funcFound)
183       DeleteFunctionBody(I);
184   }
185   return New;
186 }