Put the functionality for printing a value to a raw_ostream as an
[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 is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements several methods that are used to extract functions,
11 // loops, or portions of a module from the rest of the module.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "BugDriver.h"
16 #include "llvm/Analysis/Verifier.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Pass.h"
23 #include "llvm/PassManager.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/FileUtilities.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/Signals.h"
29 #include "llvm/Support/ToolOutputFile.h"
30 #include "llvm/Transforms/IPO.h"
31 #include "llvm/Transforms/Scalar.h"
32 #include "llvm/Transforms/Utils/Cloning.h"
33 #include "llvm/Transforms/Utils/CodeExtractor.h"
34 #include <set>
35 using namespace llvm;
36
37 namespace llvm {
38   bool DisableSimplifyCFG = false;
39   extern cl::opt<std::string> OutputPrefix;
40 } // End llvm namespace
41
42 namespace {
43   cl::opt<bool>
44   NoDCE ("disable-dce",
45          cl::desc("Do not use the -dce pass to reduce testcases"));
46   cl::opt<bool, true>
47   NoSCFG("disable-simplifycfg", cl::location(DisableSimplifyCFG),
48          cl::desc("Do not use the -simplifycfg pass to reduce testcases"));
49
50   Function* globalInitUsesExternalBA(GlobalVariable* GV) {
51     if (!GV->hasInitializer())
52       return 0;
53
54     Constant *I = GV->getInitializer();
55
56     // walk the values used by the initializer
57     // (and recurse into things like ConstantExpr)
58     std::vector<Constant*> Todo;
59     std::set<Constant*> Done;
60     Todo.push_back(I);
61
62     while (!Todo.empty()) {
63       Constant* V = Todo.back();
64       Todo.pop_back();
65       Done.insert(V);
66
67       if (BlockAddress *BA = dyn_cast<BlockAddress>(V)) {
68         Function *F = BA->getFunction();
69         if (F->isDeclaration())
70           return F;
71       }
72
73       for (User::op_iterator i = V->op_begin(), e = V->op_end(); i != e; ++i) {
74         Constant *C = dyn_cast<Constant>(*i);
75         if (C && !isa<GlobalValue>(C) && !Done.count(C))
76           Todo.push_back(C);
77       }
78     }
79     return 0;
80   }
81 }  // end anonymous namespace
82
83 /// deleteInstructionFromProgram - This method clones the current Program and
84 /// deletes the specified instruction from the cloned module.  It then runs a
85 /// series of cleanup passes (ADCE and SimplifyCFG) to eliminate any code which
86 /// depends on the value.  The modified module is then returned.
87 ///
88 Module *BugDriver::deleteInstructionFromProgram(const Instruction *I,
89                                                 unsigned Simplification) {
90   // FIXME, use vmap?
91   Module *Clone = CloneModule(Program);
92
93   const BasicBlock *PBB = I->getParent();
94   const Function *PF = PBB->getParent();
95
96   Module::iterator RFI = Clone->begin(); // Get iterator to corresponding fn
97   std::advance(RFI, std::distance(PF->getParent()->begin(),
98                                   Module::const_iterator(PF)));
99
100   Function::iterator RBI = RFI->begin();  // Get iterator to corresponding BB
101   std::advance(RBI, std::distance(PF->begin(), Function::const_iterator(PBB)));
102
103   BasicBlock::iterator RI = RBI->begin(); // Get iterator to corresponding inst
104   std::advance(RI, std::distance(PBB->begin(), BasicBlock::const_iterator(I)));
105   Instruction *TheInst = RI;              // Got the corresponding instruction!
106
107   // If this instruction produces a value, replace any users with null values
108   if (!TheInst->getType()->isVoidTy())
109     TheInst->replaceAllUsesWith(Constant::getNullValue(TheInst->getType()));
110
111   // Remove the instruction from the program.
112   TheInst->getParent()->getInstList().erase(TheInst);
113
114   // Spiff up the output a little bit.
115   std::vector<std::string> Passes;
116
117   /// Can we get rid of the -disable-* options?
118   if (Simplification > 1 && !NoDCE)
119     Passes.push_back("dce");
120   if (Simplification && !DisableSimplifyCFG)
121     Passes.push_back("simplifycfg");      // Delete dead control flow
122
123   Passes.push_back("verify");
124   Module *New = runPassesOn(Clone, Passes);
125   delete Clone;
126   if (!New) {
127     errs() << "Instruction removal failed.  Sorry. :(  Please report a bug!\n";
128     exit(1);
129   }
130   return New;
131 }
132
133 /// performFinalCleanups - This method clones the current Program and performs
134 /// a series of cleanups intended to get rid of extra cruft on the module
135 /// before handing it to the user.
136 ///
137 Module *BugDriver::performFinalCleanups(Module *M, bool MayModifySemantics) {
138   // Make all functions external, so GlobalDCE doesn't delete them...
139   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
140     I->setLinkage(GlobalValue::ExternalLinkage);
141
142   std::vector<std::string> CleanupPasses;
143   CleanupPasses.push_back("globaldce");
144
145   if (MayModifySemantics)
146     CleanupPasses.push_back("deadarghaX0r");
147   else
148     CleanupPasses.push_back("deadargelim");
149
150   Module *New = runPassesOn(M, CleanupPasses);
151   if (New == 0) {
152     errs() << "Final cleanups failed.  Sorry. :(  Please report a bug!\n";
153     return M;
154   }
155   delete M;
156   return New;
157 }
158
159
160 /// ExtractLoop - Given a module, extract up to one loop from it into a new
161 /// function.  This returns null if there are no extractable loops in the
162 /// program or if the loop extractor crashes.
163 Module *BugDriver::ExtractLoop(Module *M) {
164   std::vector<std::string> LoopExtractPasses;
165   LoopExtractPasses.push_back("loop-extract-single");
166
167   Module *NewM = runPassesOn(M, LoopExtractPasses);
168   if (NewM == 0) {
169     outs() << "*** Loop extraction failed: ";
170     EmitProgressBitcode(M, "loopextraction", true);
171     outs() << "*** Sorry. :(  Please report a bug!\n";
172     return 0;
173   }
174
175   // Check to see if we created any new functions.  If not, no loops were
176   // extracted and we should return null.  Limit the number of loops we extract
177   // to avoid taking forever.
178   static unsigned NumExtracted = 32;
179   if (M->size() == NewM->size() || --NumExtracted == 0) {
180     delete NewM;
181     return 0;
182   } else {
183     assert(M->size() < NewM->size() && "Loop extract removed functions?");
184     Module::iterator MI = NewM->begin();
185     for (unsigned i = 0, e = M->size(); i != e; ++i)
186       ++MI;
187   }
188
189   return NewM;
190 }
191
192
193 // DeleteFunctionBody - "Remove" the function by deleting all of its basic
194 // blocks, making it external.
195 //
196 void llvm::DeleteFunctionBody(Function *F) {
197   // delete the body of the function...
198   F->deleteBody();
199   assert(F->isDeclaration() && "This didn't make the function external!");
200 }
201
202 /// GetTorInit - Given a list of entries for static ctors/dtors, return them
203 /// as a constant array.
204 static Constant *GetTorInit(std::vector<std::pair<Function*, int> > &TorList) {
205   assert(!TorList.empty() && "Don't create empty tor list!");
206   std::vector<Constant*> ArrayElts;
207   Type *Int32Ty = Type::getInt32Ty(TorList[0].first->getContext());
208   
209   StructType *STy =
210     StructType::get(Int32Ty, TorList[0].first->getType(), NULL);
211   for (unsigned i = 0, e = TorList.size(); i != e; ++i) {
212     Constant *Elts[] = {
213       ConstantInt::get(Int32Ty, TorList[i].second),
214       TorList[i].first
215     };
216     ArrayElts.push_back(ConstantStruct::get(STy, Elts));
217   }
218   return ConstantArray::get(ArrayType::get(ArrayElts[0]->getType(), 
219                                            ArrayElts.size()),
220                             ArrayElts);
221 }
222
223 /// SplitStaticCtorDtor - A module was recently split into two parts, M1/M2, and
224 /// M1 has all of the global variables.  If M2 contains any functions that are
225 /// static ctors/dtors, we need to add an llvm.global_[cd]tors global to M2, and
226 /// prune appropriate entries out of M1s list.
227 static void SplitStaticCtorDtor(const char *GlobalName, Module *M1, Module *M2,
228                                 ValueToValueMapTy &VMap) {
229   GlobalVariable *GV = M1->getNamedGlobal(GlobalName);
230   if (!GV || GV->isDeclaration() || GV->hasLocalLinkage() ||
231       !GV->use_empty()) return;
232   
233   std::vector<std::pair<Function*, int> > M1Tors, M2Tors;
234   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
235   if (!InitList) return;
236   
237   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
238     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
239       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
240       
241       if (CS->getOperand(1)->isNullValue())
242         break;  // Found a null terminator, stop here.
243       
244       ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
245       int Priority = CI ? CI->getSExtValue() : 0;
246       
247       Constant *FP = CS->getOperand(1);
248       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
249         if (CE->isCast())
250           FP = CE->getOperand(0);
251       if (Function *F = dyn_cast<Function>(FP)) {
252         if (!F->isDeclaration())
253           M1Tors.push_back(std::make_pair(F, Priority));
254         else {
255           // Map to M2's version of the function.
256           F = cast<Function>(VMap[F]);
257           M2Tors.push_back(std::make_pair(F, Priority));
258         }
259       }
260     }
261   }
262   
263   GV->eraseFromParent();
264   if (!M1Tors.empty()) {
265     Constant *M1Init = GetTorInit(M1Tors);
266     new GlobalVariable(*M1, M1Init->getType(), false,
267                        GlobalValue::AppendingLinkage,
268                        M1Init, GlobalName);
269   }
270
271   GV = M2->getNamedGlobal(GlobalName);
272   assert(GV && "Not a clone of M1?");
273   assert(GV->use_empty() && "llvm.ctors shouldn't have uses!");
274
275   GV->eraseFromParent();
276   if (!M2Tors.empty()) {
277     Constant *M2Init = GetTorInit(M2Tors);
278     new GlobalVariable(*M2, M2Init->getType(), false,
279                        GlobalValue::AppendingLinkage,
280                        M2Init, GlobalName);
281   }
282 }
283
284
285 /// SplitFunctionsOutOfModule - Given a module and a list of functions in the
286 /// module, split the functions OUT of the specified module, and place them in
287 /// the new module.
288 Module *
289 llvm::SplitFunctionsOutOfModule(Module *M,
290                                 const std::vector<Function*> &F,
291                                 ValueToValueMapTy &VMap) {
292   // Make sure functions & globals are all external so that linkage
293   // between the two modules will work.
294   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
295     I->setLinkage(GlobalValue::ExternalLinkage);
296   for (Module::global_iterator I = M->global_begin(), E = M->global_end();
297        I != E; ++I) {
298     if (I->hasName() && I->getName()[0] == '\01')
299       I->setName(I->getName().substr(1));
300     I->setLinkage(GlobalValue::ExternalLinkage);
301   }
302
303   ValueToValueMapTy NewVMap;
304   Module *New = CloneModule(M, NewVMap);
305
306   // Remove the Test functions from the Safe module
307   std::set<Function *> TestFunctions;
308   for (unsigned i = 0, e = F.size(); i != e; ++i) {
309     Function *TNOF = cast<Function>(VMap[F[i]]);
310     DEBUG(errs() << "Removing function ");
311     DEBUG(TNOF->printAsOperand(errs(), false));
312     DEBUG(errs() << "\n");
313     TestFunctions.insert(cast<Function>(NewVMap[TNOF]));
314     DeleteFunctionBody(TNOF);       // Function is now external in this module!
315   }
316
317   
318   // Remove the Safe functions from the Test module
319   for (Module::iterator I = New->begin(), E = New->end(); I != E; ++I)
320     if (!TestFunctions.count(I))
321       DeleteFunctionBody(I);
322   
323
324   // Try to split the global initializers evenly
325   for (Module::global_iterator I = M->global_begin(), E = M->global_end();
326        I != E; ++I) {
327     GlobalVariable *GV = cast<GlobalVariable>(NewVMap[I]);
328     if (Function *TestFn = globalInitUsesExternalBA(I)) {
329       if (Function *SafeFn = globalInitUsesExternalBA(GV)) {
330         errs() << "*** Error: when reducing functions, encountered "
331                   "the global '";
332         GV->printAsOperand(errs(), false);
333         errs() << "' with an initializer that references blockaddresses "
334                   "from safe function '" << SafeFn->getName()
335                << "' and from test function '" << TestFn->getName() << "'.\n";
336         exit(1);
337       }
338       I->setInitializer(0);  // Delete the initializer to make it external
339     } else {
340       // If we keep it in the safe module, then delete it in the test module
341       GV->setInitializer(0);
342     }
343   }
344
345   // Make sure that there is a global ctor/dtor array in both halves of the
346   // module if they both have static ctor/dtor functions.
347   SplitStaticCtorDtor("llvm.global_ctors", M, New, NewVMap);
348   SplitStaticCtorDtor("llvm.global_dtors", M, New, NewVMap);
349   
350   return New;
351 }
352
353 //===----------------------------------------------------------------------===//
354 // Basic Block Extraction Code
355 //===----------------------------------------------------------------------===//
356
357 /// ExtractMappedBlocksFromModule - Extract all but the specified basic blocks
358 /// into their own functions.  The only detail is that M is actually a module
359 /// cloned from the one the BBs are in, so some mapping needs to be performed.
360 /// If this operation fails for some reason (ie the implementation is buggy),
361 /// this function should return null, otherwise it returns a new Module.
362 Module *BugDriver::ExtractMappedBlocksFromModule(const
363                                                  std::vector<BasicBlock*> &BBs,
364                                                  Module *M) {
365   SmallString<128> Filename;
366   int FD;
367   error_code EC = sys::fs::createUniqueFile(
368       OutputPrefix + "-extractblocks%%%%%%%", FD, Filename);
369   if (EC) {
370     outs() << "*** Basic Block extraction failed!\n";
371     errs() << "Error creating temporary file: " << EC.message() << "\n";
372     EmitProgressBitcode(M, "basicblockextractfail", true);
373     return 0;
374   }
375   sys::RemoveFileOnSignal(Filename);
376
377   tool_output_file BlocksToNotExtractFile(Filename.c_str(), FD);
378   for (std::vector<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
379        I != E; ++I) {
380     BasicBlock *BB = *I;
381     // If the BB doesn't have a name, give it one so we have something to key
382     // off of.
383     if (!BB->hasName()) BB->setName("tmpbb");
384     BlocksToNotExtractFile.os() << BB->getParent()->getName() << " "
385                                 << BB->getName() << "\n";
386   }
387   BlocksToNotExtractFile.os().close();
388   if (BlocksToNotExtractFile.os().has_error()) {
389     errs() << "Error writing list of blocks to not extract\n";
390     EmitProgressBitcode(M, "basicblockextractfail", true);
391     BlocksToNotExtractFile.os().clear_error();
392     return 0;
393   }
394   BlocksToNotExtractFile.keep();
395
396   std::string uniqueFN = "--extract-blocks-file=";
397   uniqueFN += Filename.str();
398   const char *ExtraArg = uniqueFN.c_str();
399
400   std::vector<std::string> PI;
401   PI.push_back("extract-blocks");
402   Module *Ret = runPassesOn(M, PI, false, 1, &ExtraArg);
403
404   sys::fs::remove(Filename.c_str());
405
406   if (Ret == 0) {
407     outs() << "*** Basic Block extraction failed, please report a bug!\n";
408     EmitProgressBitcode(M, "basicblockextractfail", true);
409   }
410   return Ret;
411 }