173a6bdd9SChris Lattner //===- ExtractFunction.cpp - Extract a function from Program --------------===//
273a6bdd9SChris Lattner //
309344dcfSJohn Criswell //                     The LLVM Compiler Infrastructure
409344dcfSJohn Criswell //
5345353d6SChris Lattner // This file is distributed under the University of Illinois Open Source
6345353d6SChris Lattner // License. See LICENSE.TXT for details.
709344dcfSJohn Criswell //
809344dcfSJohn Criswell //===----------------------------------------------------------------------===//
909344dcfSJohn Criswell //
10fd72bed3SChris Lattner // This file implements several methods that are used to extract functions,
11fd72bed3SChris Lattner // loops, or portions of a module from the rest of the module.
1273a6bdd9SChris Lattner //
1373a6bdd9SChris Lattner //===----------------------------------------------------------------------===//
1473a6bdd9SChris Lattner 
1573a6bdd9SChris Lattner #include "BugDriver.h"
16fdb533a1SChris Lattner #include "llvm/Constants.h"
17fdb533a1SChris Lattner #include "llvm/DerivedTypes.h"
18b258410aSOwen Anderson #include "llvm/LLVMContext.h"
1973a6bdd9SChris Lattner #include "llvm/Module.h"
2073a6bdd9SChris Lattner #include "llvm/PassManager.h"
21ef432703SBrian Gaeke #include "llvm/Pass.h"
220c2305b1SMisha Brukman #include "llvm/Analysis/Verifier.h"
23e2d31aa1SDan Gohman #include "llvm/Assembly/Writer.h"
2473a6bdd9SChris Lattner #include "llvm/Transforms/IPO.h"
250eb5ce94SChris Lattner #include "llvm/Transforms/Scalar.h"
2673a6bdd9SChris Lattner #include "llvm/Transforms/Utils/Cloning.h"
27a060b10eSChris Lattner #include "llvm/Transforms/Utils/FunctionUtils.h"
28f3e8f97dSChris Lattner #include "llvm/Target/TargetData.h"
297c16caa3SReid Spencer #include "llvm/Support/CommandLine.h"
307c16caa3SReid Spencer #include "llvm/Support/Debug.h"
317c16caa3SReid Spencer #include "llvm/Support/FileUtilities.h"
32c6243020SNick Lewycky #include "llvm/System/Path.h"
33c6243020SNick Lewycky #include "llvm/System/Signals.h"
343838243dSChris Lattner #include <set>
353f1ad878SChris Lattner using namespace llvm;
36960707c3SBrian Gaeke 
37960707c3SBrian Gaeke namespace llvm {
38d1e2aaefSChris Lattner   bool DisableSimplifyCFG = false;
39960707c3SBrian Gaeke } // End llvm namespace
40960707c3SBrian Gaeke 
418d8de422SChris Lattner namespace {
428d8de422SChris Lattner   cl::opt<bool>
438d8de422SChris Lattner   NoDCE ("disable-dce",
448d8de422SChris Lattner          cl::desc("Do not use the -dce pass to reduce testcases"));
45d1e2aaefSChris Lattner   cl::opt<bool, true>
46d1e2aaefSChris Lattner   NoSCFG("disable-simplifycfg", cl::location(DisableSimplifyCFG),
478d8de422SChris Lattner          cl::desc("Do not use the -simplifycfg pass to reduce testcases"));
488d8de422SChris Lattner }
4973a6bdd9SChris Lattner 
500eb5ce94SChris Lattner /// deleteInstructionFromProgram - This method clones the current Program and
510eb5ce94SChris Lattner /// deletes the specified instruction from the cloned module.  It then runs a
520eb5ce94SChris Lattner /// series of cleanup passes (ADCE and SimplifyCFG) to eliminate any code which
530eb5ce94SChris Lattner /// depends on the value.  The modified module is then returned.
540eb5ce94SChris Lattner ///
55b943b6b0SChris Lattner Module *BugDriver::deleteInstructionFromProgram(const Instruction *I,
560eb5ce94SChris Lattner                                                 unsigned Simplification) const {
570eb5ce94SChris Lattner   Module *Result = CloneModule(Program);
580eb5ce94SChris Lattner 
59b943b6b0SChris Lattner   const BasicBlock *PBB = I->getParent();
60b943b6b0SChris Lattner   const Function *PF = PBB->getParent();
610eb5ce94SChris Lattner 
620eb5ce94SChris Lattner   Module::iterator RFI = Result->begin(); // Get iterator to corresponding fn
63b943b6b0SChris Lattner   std::advance(RFI, std::distance(PF->getParent()->begin(),
64b943b6b0SChris Lattner                                   Module::const_iterator(PF)));
650eb5ce94SChris Lattner 
660eb5ce94SChris Lattner   Function::iterator RBI = RFI->begin();  // Get iterator to corresponding BB
67b943b6b0SChris Lattner   std::advance(RBI, std::distance(PF->begin(), Function::const_iterator(PBB)));
680eb5ce94SChris Lattner 
690eb5ce94SChris Lattner   BasicBlock::iterator RI = RBI->begin(); // Get iterator to corresponding inst
70b943b6b0SChris Lattner   std::advance(RI, std::distance(PBB->begin(), BasicBlock::const_iterator(I)));
71b943b6b0SChris Lattner   Instruction *TheInst = RI;              // Got the corresponding instruction!
720eb5ce94SChris Lattner 
730eb5ce94SChris Lattner   // If this instruction produces a value, replace any users with null values
747855a5cbSChris Lattner   if (isa<StructType>(TheInst->getType()))
75b292b8ceSOwen Anderson     TheInst->replaceAllUsesWith(UndefValue::get(TheInst->getType()));
7655f1c09eSOwen Anderson   else if (TheInst->getType() != Type::getVoidTy(I->getContext()))
775a1acd99SOwen Anderson     TheInst->replaceAllUsesWith(Constant::getNullValue(TheInst->getType()));
780eb5ce94SChris Lattner 
790eb5ce94SChris Lattner   // Remove the instruction from the program.
80b943b6b0SChris Lattner   TheInst->getParent()->getInstList().erase(TheInst);
810eb5ce94SChris Lattner 
82fdb533a1SChris Lattner 
83fdb533a1SChris Lattner   //writeProgramToFile("current.bc", Result);
84fdb533a1SChris Lattner 
8510c0469bSChris Lattner   // Spiff up the output a little bit.
860eb5ce94SChris Lattner   PassManager Passes;
87f3e8f97dSChris Lattner   // Make sure that the appropriate target data is always used...
8816cf8130SChris Lattner   Passes.add(new TargetData(Result));
89f3e8f97dSChris Lattner 
90fd72bed3SChris Lattner   /// FIXME: If this used runPasses() like the methods below, we could get rid
91fd72bed3SChris Lattner   /// of the -disable-* options!
928d8de422SChris Lattner   if (Simplification > 1 && !NoDCE)
930eb5ce94SChris Lattner     Passes.add(createDeadCodeEliminationPass());
94d1e2aaefSChris Lattner   if (Simplification && !DisableSimplifyCFG)
950eb5ce94SChris Lattner     Passes.add(createCFGSimplificationPass());      // Delete dead control flow
9644ffd7c3SChris Lattner 
9744ffd7c3SChris Lattner   Passes.add(createVerifierPass());
980eb5ce94SChris Lattner   Passes.run(*Result);
990eb5ce94SChris Lattner   return Result;
1000eb5ce94SChris Lattner }
101514c02ebSChris Lattner 
1022920100eSChris Lattner static const PassInfo *getPI(Pass *P) {
1032920100eSChris Lattner   const PassInfo *PI = P->getPassInfo();
1042920100eSChris Lattner   delete P;
1052920100eSChris Lattner   return PI;
1062920100eSChris Lattner }
1072920100eSChris Lattner 
108514c02ebSChris Lattner /// performFinalCleanups - This method clones the current Program and performs
109514c02ebSChris Lattner /// a series of cleanups intended to get rid of extra cruft on the module
1105e166a5fSChris Lattner /// before handing it to the user.
111514c02ebSChris Lattner ///
1122920100eSChris Lattner Module *BugDriver::performFinalCleanups(Module *M, bool MayModifySemantics) {
1132b3ab562SChris Lattner   // Make all functions external, so GlobalDCE doesn't delete them...
1142b3ab562SChris Lattner   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
1152b3ab562SChris Lattner     I->setLinkage(GlobalValue::ExternalLinkage);
1162b3ab562SChris Lattner 
1172920100eSChris Lattner   std::vector<const PassInfo*> CleanupPasses;
1182920100eSChris Lattner   CleanupPasses.push_back(getPI(createGlobalDCEPass()));
1192920100eSChris Lattner   CleanupPasses.push_back(getPI(createDeadTypeEliminationPass()));
1203f1ad878SChris Lattner 
1213f1ad878SChris Lattner   if (MayModifySemantics)
1222920100eSChris Lattner     CleanupPasses.push_back(getPI(createDeadArgHackingPass()));
1233f1ad878SChris Lattner   else
1243f1ad878SChris Lattner     CleanupPasses.push_back(getPI(createDeadArgEliminationPass()));
1252920100eSChris Lattner 
1266ce2d033SChris Lattner   Module *New = runPassesOn(M, CleanupPasses);
1276ce2d033SChris Lattner   if (New == 0) {
128d8db3760SDan Gohman     errs() << "Final cleanups failed.  Sorry. :(  Please report a bug!\n";
1295e166a5fSChris Lattner     return M;
1306ce2d033SChris Lattner   }
1312920100eSChris Lattner   delete M;
1326ce2d033SChris Lattner   return New;
133514c02ebSChris Lattner }
134567543f0SChris Lattner 
135567543f0SChris Lattner 
1363fe96bc9SChris Lattner /// ExtractLoop - Given a module, extract up to one loop from it into a new
1373fe96bc9SChris Lattner /// function.  This returns null if there are no extractable loops in the
1383fe96bc9SChris Lattner /// program or if the loop extractor crashes.
1393fe96bc9SChris Lattner Module *BugDriver::ExtractLoop(Module *M) {
1403fe96bc9SChris Lattner   std::vector<const PassInfo*> LoopExtractPasses;
1413fe96bc9SChris Lattner   LoopExtractPasses.push_back(getPI(createSingleLoopExtractorPass()));
1423fe96bc9SChris Lattner 
1436ce2d033SChris Lattner   Module *NewM = runPassesOn(M, LoopExtractPasses);
1446ce2d033SChris Lattner   if (NewM == 0) {
145bcec7875SChris Lattner     Module *Old = swapProgramIn(M);
146ee05152cSDan Gohman     outs() << "*** Loop extraction failed: ";
1470e535c3cSGabor Greif     EmitProgressBitcode("loopextraction", true);
148ee05152cSDan Gohman     outs() << "*** Sorry. :(  Please report a bug!\n";
149bcec7875SChris Lattner     swapProgramIn(Old);
1503fe96bc9SChris Lattner     return 0;
1513fe96bc9SChris Lattner   }
1523fe96bc9SChris Lattner 
1533fe96bc9SChris Lattner   // Check to see if we created any new functions.  If not, no loops were
1548cb483b3SChris Lattner   // extracted and we should return null.  Limit the number of loops we extract
1558cb483b3SChris Lattner   // to avoid taking forever.
1568cb483b3SChris Lattner   static unsigned NumExtracted = 32;
157d308797cSChris Lattner   if (M->size() == NewM->size() || --NumExtracted == 0) {
1583fe96bc9SChris Lattner     delete NewM;
1593fe96bc9SChris Lattner     return 0;
160d308797cSChris Lattner   } else {
161d308797cSChris Lattner     assert(M->size() < NewM->size() && "Loop extract removed functions?");
162d308797cSChris Lattner     Module::iterator MI = NewM->begin();
163d308797cSChris Lattner     for (unsigned i = 0, e = M->size(); i != e; ++i)
164d308797cSChris Lattner       ++MI;
1653fe96bc9SChris Lattner   }
1663fe96bc9SChris Lattner 
1673fe96bc9SChris Lattner   return NewM;
1683fe96bc9SChris Lattner }
1693fe96bc9SChris Lattner 
1703fe96bc9SChris Lattner 
171567543f0SChris Lattner // DeleteFunctionBody - "Remove" the function by deleting all of its basic
172567543f0SChris Lattner // blocks, making it external.
173567543f0SChris Lattner //
174567543f0SChris Lattner void llvm::DeleteFunctionBody(Function *F) {
175567543f0SChris Lattner   // delete the body of the function...
176567543f0SChris Lattner   F->deleteBody();
1775301e7c6SReid Spencer   assert(F->isDeclaration() && "This didn't make the function external!");
178567543f0SChris Lattner }
179567543f0SChris Lattner 
180fdb533a1SChris Lattner /// GetTorInit - Given a list of entries for static ctors/dtors, return them
181fdb533a1SChris Lattner /// as a constant array.
182fdb533a1SChris Lattner static Constant *GetTorInit(std::vector<std::pair<Function*, int> > &TorList) {
183fdb533a1SChris Lattner   assert(!TorList.empty() && "Don't create empty tor list!");
184fdb533a1SChris Lattner   std::vector<Constant*> ArrayElts;
185fdb533a1SChris Lattner   for (unsigned i = 0, e = TorList.size(); i != e; ++i) {
186fdb533a1SChris Lattner     std::vector<Constant*> Elts;
18755f1c09eSOwen Anderson     Elts.push_back(ConstantInt::get(
18855f1c09eSOwen Anderson           Type::getInt32Ty(TorList[i].first->getContext()), TorList[i].second));
189fdb533a1SChris Lattner     Elts.push_back(TorList[i].first);
19003cb69fbSOwen Anderson     ArrayElts.push_back(ConstantStruct::get(
19103cb69fbSOwen Anderson                                         TorList[i].first->getContext(), Elts));
192fdb533a1SChris Lattner   }
1934056ca95SOwen Anderson   return ConstantArray::get(ArrayType::get(ArrayElts[0]->getType(),
194fdb533a1SChris Lattner                                            ArrayElts.size()),
195fdb533a1SChris Lattner                             ArrayElts);
196fdb533a1SChris Lattner }
197fdb533a1SChris Lattner 
198fdb533a1SChris Lattner /// SplitStaticCtorDtor - A module was recently split into two parts, M1/M2, and
199fdb533a1SChris Lattner /// M1 has all of the global variables.  If M2 contains any functions that are
200fdb533a1SChris Lattner /// static ctors/dtors, we need to add an llvm.global_[cd]tors global to M2, and
201fdb533a1SChris Lattner /// prune appropriate entries out of M1s list.
202956ae9dcSDan Gohman static void SplitStaticCtorDtor(const char *GlobalName, Module *M1, Module *M2,
203956ae9dcSDan Gohman                                 DenseMap<const Value*, Value*> ValueMap) {
204fdb533a1SChris Lattner   GlobalVariable *GV = M1->getNamedGlobal(GlobalName);
2056de96a1bSRafael Espindola   if (!GV || GV->isDeclaration() || GV->hasLocalLinkage() ||
206fdb533a1SChris Lattner       !GV->use_empty()) return;
207fdb533a1SChris Lattner 
208fdb533a1SChris Lattner   std::vector<std::pair<Function*, int> > M1Tors, M2Tors;
209fdb533a1SChris Lattner   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
210fdb533a1SChris Lattner   if (!InitList) return;
211fdb533a1SChris Lattner 
212fdb533a1SChris Lattner   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
213fdb533a1SChris Lattner     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
214fdb533a1SChris Lattner       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
215fdb533a1SChris Lattner 
216fdb533a1SChris Lattner       if (CS->getOperand(1)->isNullValue())
217fdb533a1SChris Lattner         break;  // Found a null terminator, stop here.
218fdb533a1SChris Lattner 
219e0fc4dfcSReid Spencer       ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
220e0fc4dfcSReid Spencer       int Priority = CI ? CI->getSExtValue() : 0;
221fdb533a1SChris Lattner 
222fdb533a1SChris Lattner       Constant *FP = CS->getOperand(1);
223fdb533a1SChris Lattner       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
2246c38f0bbSReid Spencer         if (CE->isCast())
225fdb533a1SChris Lattner           FP = CE->getOperand(0);
226fdb533a1SChris Lattner       if (Function *F = dyn_cast<Function>(FP)) {
2275301e7c6SReid Spencer         if (!F->isDeclaration())
228fdb533a1SChris Lattner           M1Tors.push_back(std::make_pair(F, Priority));
229fdb533a1SChris Lattner         else {
230fdb533a1SChris Lattner           // Map to M2's version of the function.
231956ae9dcSDan Gohman           F = cast<Function>(ValueMap[F]);
232fdb533a1SChris Lattner           M2Tors.push_back(std::make_pair(F, Priority));
233fdb533a1SChris Lattner         }
234fdb533a1SChris Lattner       }
235fdb533a1SChris Lattner     }
236fdb533a1SChris Lattner   }
237fdb533a1SChris Lattner 
238fdb533a1SChris Lattner   GV->eraseFromParent();
239fdb533a1SChris Lattner   if (!M1Tors.empty()) {
240fdb533a1SChris Lattner     Constant *M1Init = GetTorInit(M1Tors);
241b17f3294SOwen Anderson     new GlobalVariable(*M1, M1Init->getType(), false,
2425948fdf6SOwen Anderson                        GlobalValue::AppendingLinkage,
243b17f3294SOwen Anderson                        M1Init, GlobalName);
244fdb533a1SChris Lattner   }
245fdb533a1SChris Lattner 
246fdb533a1SChris Lattner   GV = M2->getNamedGlobal(GlobalName);
247fdb533a1SChris Lattner   assert(GV && "Not a clone of M1?");
248fdb533a1SChris Lattner   assert(GV->use_empty() && "llvm.ctors shouldn't have uses!");
249fdb533a1SChris Lattner 
250fdb533a1SChris Lattner   GV->eraseFromParent();
251fdb533a1SChris Lattner   if (!M2Tors.empty()) {
252fdb533a1SChris Lattner     Constant *M2Init = GetTorInit(M2Tors);
253b17f3294SOwen Anderson     new GlobalVariable(*M2, M2Init->getType(), false,
2545948fdf6SOwen Anderson                        GlobalValue::AppendingLinkage,
255b17f3294SOwen Anderson                        M2Init, GlobalName);
256fdb533a1SChris Lattner   }
257fdb533a1SChris Lattner }
258fdb533a1SChris Lattner 
259b417a5c1SPatrick Jenkins 
260567543f0SChris Lattner /// SplitFunctionsOutOfModule - Given a module and a list of functions in the
261567543f0SChris Lattner /// module, split the functions OUT of the specified module, and place them in
262567543f0SChris Lattner /// the new module.
263956ae9dcSDan Gohman Module *
264956ae9dcSDan Gohman llvm::SplitFunctionsOutOfModule(Module *M,
265956ae9dcSDan Gohman                                 const std::vector<Function*> &F,
266956ae9dcSDan Gohman                                 DenseMap<const Value*, Value*> &ValueMap) {
267567543f0SChris Lattner   // Make sure functions & globals are all external so that linkage
268567543f0SChris Lattner   // between the two modules will work.
269567543f0SChris Lattner   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
270567543f0SChris Lattner     I->setLinkage(GlobalValue::ExternalLinkage);
271fdb533a1SChris Lattner   for (Module::global_iterator I = M->global_begin(), E = M->global_end();
272c76bacbfSOwen Anderson        I != E; ++I) {
273d786b51eSDaniel Dunbar     if (I->hasName() && I->getName()[0] == '\01')
274d786b51eSDaniel Dunbar       I->setName(I->getName().substr(1));
275567543f0SChris Lattner     I->setLinkage(GlobalValue::ExternalLinkage);
276c76bacbfSOwen Anderson   }
277567543f0SChris Lattner 
278956ae9dcSDan Gohman   DenseMap<const Value*, Value*> NewValueMap;
279956ae9dcSDan Gohman   Module *New = CloneModule(M, NewValueMap);
280567543f0SChris Lattner 
2817275b02eSChris Lattner   // Make sure global initializers exist only in the safe module (CBE->.so)
2827275b02eSChris Lattner   for (Module::global_iterator I = New->global_begin(), E = New->global_end();
2837275b02eSChris Lattner        I != E; ++I)
2847275b02eSChris Lattner     I->setInitializer(0);  // Delete the initializer to make it external
285567543f0SChris Lattner 
2867275b02eSChris Lattner   // Remove the Test functions from the Safe module
287956ae9dcSDan Gohman   std::set<Function *> TestFunctions;
288567543f0SChris Lattner   for (unsigned i = 0, e = F.size(); i != e; ++i) {
289956ae9dcSDan Gohman     Function *TNOF = cast<Function>(ValueMap[F[i]]);
290d8db3760SDan Gohman     DEBUG(errs() << "Removing function ");
291d8db3760SDan Gohman     DEBUG(WriteAsOperand(errs(), TNOF, false));
292d8db3760SDan Gohman     DEBUG(errs() << "\n");
293956ae9dcSDan Gohman     TestFunctions.insert(cast<Function>(NewValueMap[TNOF]));
2947275b02eSChris Lattner     DeleteFunctionBody(TNOF);       // Function is now external in this module!
295567543f0SChris Lattner   }
296567543f0SChris Lattner 
297b417a5c1SPatrick Jenkins 
2987275b02eSChris Lattner   // Remove the Safe functions from the Test module
2997275b02eSChris Lattner   for (Module::iterator I = New->begin(), E = New->end(); I != E; ++I)
300956ae9dcSDan Gohman     if (!TestFunctions.count(I))
3017275b02eSChris Lattner       DeleteFunctionBody(I);
302b417a5c1SPatrick Jenkins 
303fdb533a1SChris Lattner 
304fdb533a1SChris Lattner   // Make sure that there is a global ctor/dtor array in both halves of the
305fdb533a1SChris Lattner   // module if they both have static ctor/dtor functions.
306956ae9dcSDan Gohman   SplitStaticCtorDtor("llvm.global_ctors", M, New, NewValueMap);
307956ae9dcSDan Gohman   SplitStaticCtorDtor("llvm.global_dtors", M, New, NewValueMap);
308fdb533a1SChris Lattner 
309567543f0SChris Lattner   return New;
310567543f0SChris Lattner }
311a060b10eSChris Lattner 
312a060b10eSChris Lattner //===----------------------------------------------------------------------===//
313a060b10eSChris Lattner // Basic Block Extraction Code
314a060b10eSChris Lattner //===----------------------------------------------------------------------===//
315a060b10eSChris Lattner 
316a060b10eSChris Lattner /// ExtractMappedBlocksFromModule - Extract all but the specified basic blocks
317a060b10eSChris Lattner /// into their own functions.  The only detail is that M is actually a module
318a060b10eSChris Lattner /// cloned from the one the BBs are in, so some mapping needs to be performed.
319a060b10eSChris Lattner /// If this operation fails for some reason (ie the implementation is buggy),
320a060b10eSChris Lattner /// this function should return null, otherwise it returns a new Module.
321a060b10eSChris Lattner Module *BugDriver::ExtractMappedBlocksFromModule(const
322a060b10eSChris Lattner                                                  std::vector<BasicBlock*> &BBs,
323a060b10eSChris Lattner                                                  Module *M) {
324c6243020SNick Lewycky   char *ExtraArg = NULL;
325c6243020SNick Lewycky 
326c6243020SNick Lewycky   sys::Path uniqueFilename("bugpoint-extractblocks");
327c6243020SNick Lewycky   std::string ErrMsg;
328c6243020SNick Lewycky   if (uniqueFilename.createTemporaryFileOnDisk(true, &ErrMsg)) {
329ee05152cSDan Gohman     outs() << "*** Basic Block extraction failed!\n";
330d8db3760SDan Gohman     errs() << "Error creating temporary file: " << ErrMsg << "\n";
331c6243020SNick Lewycky     M = swapProgramIn(M);
332c6243020SNick Lewycky     EmitProgressBitcode("basicblockextractfail", true);
333c6243020SNick Lewycky     swapProgramIn(M);
334c6243020SNick Lewycky     return 0;
335c6243020SNick Lewycky   }
336c6243020SNick Lewycky   sys::RemoveFileOnSignal(uniqueFilename);
337c6243020SNick Lewycky 
338ee05152cSDan Gohman   std::string ErrorInfo;
339*9e6f1f16SChris Lattner   raw_fd_ostream BlocksToNotExtractFile(uniqueFilename.c_str(), ErrorInfo,
340*9e6f1f16SChris Lattner                                         raw_fd_ostream::F_Force);
341ee05152cSDan Gohman   if (!ErrorInfo.empty()) {
342ee05152cSDan Gohman     outs() << "*** Basic Block extraction failed!\n";
343ee05152cSDan Gohman     errs() << "Error writing list of blocks to not extract: " << ErrorInfo
344c6243020SNick Lewycky            << "\n";
345c6243020SNick Lewycky     M = swapProgramIn(M);
346c6243020SNick Lewycky     EmitProgressBitcode("basicblockextractfail", true);
347c6243020SNick Lewycky     swapProgramIn(M);
348c6243020SNick Lewycky     return 0;
349c6243020SNick Lewycky   }
350c6243020SNick Lewycky   for (std::vector<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
351c6243020SNick Lewycky        I != E; ++I) {
352c6243020SNick Lewycky     BasicBlock *BB = *I;
35397879424SChris Lattner     // If the BB doesn't have a name, give it one so we have something to key
35497879424SChris Lattner     // off of.
35597879424SChris Lattner     if (!BB->hasName()) BB->setName("tmpbb");
35612368685SDaniel Dunbar     BlocksToNotExtractFile << BB->getParent()->getNameStr() << " "
357c6243020SNick Lewycky                            << BB->getName() << "\n";
358c6243020SNick Lewycky   }
359c6243020SNick Lewycky   BlocksToNotExtractFile.close();
360c6243020SNick Lewycky 
361c6243020SNick Lewycky   const char *uniqueFN = uniqueFilename.c_str();
362c6243020SNick Lewycky   ExtraArg = (char*)malloc(23 + strlen(uniqueFN));
363c6243020SNick Lewycky   strcat(strcpy(ExtraArg, "--extract-blocks-file="), uniqueFN);
364c6243020SNick Lewycky 
365a060b10eSChris Lattner   std::vector<const PassInfo*> PI;
366c6243020SNick Lewycky   std::vector<BasicBlock *> EmptyBBs; // This parameter is ignored.
367c6243020SNick Lewycky   PI.push_back(getPI(createBlockExtractorPass(EmptyBBs)));
368c6243020SNick Lewycky   Module *Ret = runPassesOn(M, PI, false, 1, &ExtraArg);
369c6243020SNick Lewycky 
370c6243020SNick Lewycky   if (uniqueFilename.exists())
371c6243020SNick Lewycky     uniqueFilename.eraseFromDisk(); // Free disk space
372c6243020SNick Lewycky   free(ExtraArg);
373c6243020SNick Lewycky 
374af32dfa0SChris Lattner   if (Ret == 0) {
375ee05152cSDan Gohman     outs() << "*** Basic Block extraction failed, please report a bug!\n";
376af32dfa0SChris Lattner     M = swapProgramIn(M);
3770e535c3cSGabor Greif     EmitProgressBitcode("basicblockextractfail", true);
378917f8fd1SChris Lattner     swapProgramIn(M);
379af32dfa0SChris Lattner   }
380a060b10eSChris Lattner   return Ret;
381a060b10eSChris Lattner }
382