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"
32c521f541SChris Lattner #include "llvm/Support/raw_ostream.h"
33c6243020SNick Lewycky #include "llvm/System/Path.h"
34c6243020SNick Lewycky #include "llvm/System/Signals.h"
353838243dSChris Lattner #include <set>
363f1ad878SChris Lattner using namespace llvm;
37960707c3SBrian Gaeke 
38960707c3SBrian Gaeke namespace llvm {
39d1e2aaefSChris Lattner   bool DisableSimplifyCFG = false;
40a53337f7SDaniel Dunbar   extern cl::opt<std::string> OutputPrefix;
41960707c3SBrian Gaeke } // End llvm namespace
42960707c3SBrian Gaeke 
438d8de422SChris Lattner namespace {
448d8de422SChris Lattner   cl::opt<bool>
458d8de422SChris Lattner   NoDCE ("disable-dce",
468d8de422SChris Lattner          cl::desc("Do not use the -dce pass to reduce testcases"));
47d1e2aaefSChris Lattner   cl::opt<bool, true>
48d1e2aaefSChris Lattner   NoSCFG("disable-simplifycfg", cl::location(DisableSimplifyCFG),
498d8de422SChris Lattner          cl::desc("Do not use the -simplifycfg pass to reduce testcases"));
508d8de422SChris Lattner }
5173a6bdd9SChris Lattner 
520eb5ce94SChris Lattner /// deleteInstructionFromProgram - This method clones the current Program and
530eb5ce94SChris Lattner /// deletes the specified instruction from the cloned module.  It then runs a
540eb5ce94SChris Lattner /// series of cleanup passes (ADCE and SimplifyCFG) to eliminate any code which
550eb5ce94SChris Lattner /// depends on the value.  The modified module is then returned.
560eb5ce94SChris Lattner ///
57b943b6b0SChris Lattner Module *BugDriver::deleteInstructionFromProgram(const Instruction *I,
580eb5ce94SChris Lattner                                                 unsigned Simplification) const {
590eb5ce94SChris Lattner   Module *Result = CloneModule(Program);
600eb5ce94SChris Lattner 
61b943b6b0SChris Lattner   const BasicBlock *PBB = I->getParent();
62b943b6b0SChris Lattner   const Function *PF = PBB->getParent();
630eb5ce94SChris Lattner 
640eb5ce94SChris Lattner   Module::iterator RFI = Result->begin(); // Get iterator to corresponding fn
65b943b6b0SChris Lattner   std::advance(RFI, std::distance(PF->getParent()->begin(),
66b943b6b0SChris Lattner                                   Module::const_iterator(PF)));
670eb5ce94SChris Lattner 
680eb5ce94SChris Lattner   Function::iterator RBI = RFI->begin();  // Get iterator to corresponding BB
69b943b6b0SChris Lattner   std::advance(RBI, std::distance(PF->begin(), Function::const_iterator(PBB)));
700eb5ce94SChris Lattner 
710eb5ce94SChris Lattner   BasicBlock::iterator RI = RBI->begin(); // Get iterator to corresponding inst
72b943b6b0SChris Lattner   std::advance(RI, std::distance(PBB->begin(), BasicBlock::const_iterator(I)));
73b943b6b0SChris Lattner   Instruction *TheInst = RI;              // Got the corresponding instruction!
740eb5ce94SChris Lattner 
750eb5ce94SChris Lattner   // If this instruction produces a value, replace any users with null values
767855a5cbSChris Lattner   if (isa<StructType>(TheInst->getType()))
77b292b8ceSOwen Anderson     TheInst->replaceAllUsesWith(UndefValue::get(TheInst->getType()));
7855f1c09eSOwen Anderson   else if (TheInst->getType() != Type::getVoidTy(I->getContext()))
795a1acd99SOwen Anderson     TheInst->replaceAllUsesWith(Constant::getNullValue(TheInst->getType()));
800eb5ce94SChris Lattner 
810eb5ce94SChris Lattner   // Remove the instruction from the program.
82b943b6b0SChris Lattner   TheInst->getParent()->getInstList().erase(TheInst);
830eb5ce94SChris Lattner 
84fdb533a1SChris Lattner 
85fdb533a1SChris Lattner   //writeProgramToFile("current.bc", Result);
86fdb533a1SChris Lattner 
8710c0469bSChris Lattner   // Spiff up the output a little bit.
880eb5ce94SChris Lattner   PassManager Passes;
89f3e8f97dSChris Lattner   // Make sure that the appropriate target data is always used...
9016cf8130SChris Lattner   Passes.add(new TargetData(Result));
91f3e8f97dSChris Lattner 
92fd72bed3SChris Lattner   /// FIXME: If this used runPasses() like the methods below, we could get rid
93fd72bed3SChris Lattner   /// of the -disable-* options!
948d8de422SChris Lattner   if (Simplification > 1 && !NoDCE)
950eb5ce94SChris Lattner     Passes.add(createDeadCodeEliminationPass());
96d1e2aaefSChris Lattner   if (Simplification && !DisableSimplifyCFG)
970eb5ce94SChris Lattner     Passes.add(createCFGSimplificationPass());      // Delete dead control flow
9844ffd7c3SChris Lattner 
9944ffd7c3SChris Lattner   Passes.add(createVerifierPass());
1000eb5ce94SChris Lattner   Passes.run(*Result);
1010eb5ce94SChris Lattner   return Result;
1020eb5ce94SChris Lattner }
103514c02ebSChris Lattner 
1042920100eSChris Lattner static const PassInfo *getPI(Pass *P) {
1052920100eSChris Lattner   const PassInfo *PI = P->getPassInfo();
1062920100eSChris Lattner   delete P;
1072920100eSChris Lattner   return PI;
1082920100eSChris Lattner }
1092920100eSChris Lattner 
110514c02ebSChris Lattner /// performFinalCleanups - This method clones the current Program and performs
111514c02ebSChris Lattner /// a series of cleanups intended to get rid of extra cruft on the module
1125e166a5fSChris Lattner /// before handing it to the user.
113514c02ebSChris Lattner ///
1142920100eSChris Lattner Module *BugDriver::performFinalCleanups(Module *M, bool MayModifySemantics) {
1152b3ab562SChris Lattner   // Make all functions external, so GlobalDCE doesn't delete them...
1162b3ab562SChris Lattner   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
1172b3ab562SChris Lattner     I->setLinkage(GlobalValue::ExternalLinkage);
1182b3ab562SChris Lattner 
1192920100eSChris Lattner   std::vector<const PassInfo*> CleanupPasses;
1202920100eSChris Lattner   CleanupPasses.push_back(getPI(createGlobalDCEPass()));
1212920100eSChris Lattner   CleanupPasses.push_back(getPI(createDeadTypeEliminationPass()));
1223f1ad878SChris Lattner 
1233f1ad878SChris Lattner   if (MayModifySemantics)
1242920100eSChris Lattner     CleanupPasses.push_back(getPI(createDeadArgHackingPass()));
1253f1ad878SChris Lattner   else
1263f1ad878SChris Lattner     CleanupPasses.push_back(getPI(createDeadArgEliminationPass()));
1272920100eSChris Lattner 
1286ce2d033SChris Lattner   Module *New = runPassesOn(M, CleanupPasses);
1296ce2d033SChris Lattner   if (New == 0) {
130d8db3760SDan Gohman     errs() << "Final cleanups failed.  Sorry. :(  Please report a bug!\n";
1315e166a5fSChris Lattner     return M;
1326ce2d033SChris Lattner   }
1332920100eSChris Lattner   delete M;
1346ce2d033SChris Lattner   return New;
135514c02ebSChris Lattner }
136567543f0SChris Lattner 
137567543f0SChris Lattner 
1383fe96bc9SChris Lattner /// ExtractLoop - Given a module, extract up to one loop from it into a new
1393fe96bc9SChris Lattner /// function.  This returns null if there are no extractable loops in the
1403fe96bc9SChris Lattner /// program or if the loop extractor crashes.
1413fe96bc9SChris Lattner Module *BugDriver::ExtractLoop(Module *M) {
1423fe96bc9SChris Lattner   std::vector<const PassInfo*> LoopExtractPasses;
1433fe96bc9SChris Lattner   LoopExtractPasses.push_back(getPI(createSingleLoopExtractorPass()));
1443fe96bc9SChris Lattner 
1456ce2d033SChris Lattner   Module *NewM = runPassesOn(M, LoopExtractPasses);
1466ce2d033SChris Lattner   if (NewM == 0) {
147bcec7875SChris Lattner     Module *Old = swapProgramIn(M);
148ee05152cSDan Gohman     outs() << "*** Loop extraction failed: ";
1490e535c3cSGabor Greif     EmitProgressBitcode("loopextraction", true);
150ee05152cSDan Gohman     outs() << "*** Sorry. :(  Please report a bug!\n";
151bcec7875SChris Lattner     swapProgramIn(Old);
1523fe96bc9SChris Lattner     return 0;
1533fe96bc9SChris Lattner   }
1543fe96bc9SChris Lattner 
1553fe96bc9SChris Lattner   // Check to see if we created any new functions.  If not, no loops were
1568cb483b3SChris Lattner   // extracted and we should return null.  Limit the number of loops we extract
1578cb483b3SChris Lattner   // to avoid taking forever.
1588cb483b3SChris Lattner   static unsigned NumExtracted = 32;
159d308797cSChris Lattner   if (M->size() == NewM->size() || --NumExtracted == 0) {
1603fe96bc9SChris Lattner     delete NewM;
1613fe96bc9SChris Lattner     return 0;
162d308797cSChris Lattner   } else {
163d308797cSChris Lattner     assert(M->size() < NewM->size() && "Loop extract removed functions?");
164d308797cSChris Lattner     Module::iterator MI = NewM->begin();
165d308797cSChris Lattner     for (unsigned i = 0, e = M->size(); i != e; ++i)
166d308797cSChris Lattner       ++MI;
1673fe96bc9SChris Lattner   }
1683fe96bc9SChris Lattner 
1693fe96bc9SChris Lattner   return NewM;
1703fe96bc9SChris Lattner }
1713fe96bc9SChris Lattner 
1723fe96bc9SChris Lattner 
173567543f0SChris Lattner // DeleteFunctionBody - "Remove" the function by deleting all of its basic
174567543f0SChris Lattner // blocks, making it external.
175567543f0SChris Lattner //
176567543f0SChris Lattner void llvm::DeleteFunctionBody(Function *F) {
177567543f0SChris Lattner   // delete the body of the function...
178567543f0SChris Lattner   F->deleteBody();
1795301e7c6SReid Spencer   assert(F->isDeclaration() && "This didn't make the function external!");
180567543f0SChris Lattner }
181567543f0SChris Lattner 
182fdb533a1SChris Lattner /// GetTorInit - Given a list of entries for static ctors/dtors, return them
183fdb533a1SChris Lattner /// as a constant array.
184fdb533a1SChris Lattner static Constant *GetTorInit(std::vector<std::pair<Function*, int> > &TorList) {
185fdb533a1SChris Lattner   assert(!TorList.empty() && "Don't create empty tor list!");
186fdb533a1SChris Lattner   std::vector<Constant*> ArrayElts;
187fdb533a1SChris Lattner   for (unsigned i = 0, e = TorList.size(); i != e; ++i) {
188fdb533a1SChris Lattner     std::vector<Constant*> Elts;
18955f1c09eSOwen Anderson     Elts.push_back(ConstantInt::get(
19055f1c09eSOwen Anderson           Type::getInt32Ty(TorList[i].first->getContext()), TorList[i].second));
191fdb533a1SChris Lattner     Elts.push_back(TorList[i].first);
192*1303c0abSNick Lewycky     ArrayElts.push_back(ConstantStruct::get(TorList[i].first->getContext(),
193*1303c0abSNick Lewycky                                             Elts, false));
194fdb533a1SChris Lattner   }
1954056ca95SOwen Anderson   return ConstantArray::get(ArrayType::get(ArrayElts[0]->getType(),
196fdb533a1SChris Lattner                                            ArrayElts.size()),
197fdb533a1SChris Lattner                             ArrayElts);
198fdb533a1SChris Lattner }
199fdb533a1SChris Lattner 
200fdb533a1SChris Lattner /// SplitStaticCtorDtor - A module was recently split into two parts, M1/M2, and
201fdb533a1SChris Lattner /// M1 has all of the global variables.  If M2 contains any functions that are
202fdb533a1SChris Lattner /// static ctors/dtors, we need to add an llvm.global_[cd]tors global to M2, and
203fdb533a1SChris Lattner /// prune appropriate entries out of M1s list.
204956ae9dcSDan Gohman static void SplitStaticCtorDtor(const char *GlobalName, Module *M1, Module *M2,
205956ae9dcSDan Gohman                                 DenseMap<const Value*, Value*> ValueMap) {
206fdb533a1SChris Lattner   GlobalVariable *GV = M1->getNamedGlobal(GlobalName);
2076de96a1bSRafael Espindola   if (!GV || GV->isDeclaration() || GV->hasLocalLinkage() ||
208fdb533a1SChris Lattner       !GV->use_empty()) return;
209fdb533a1SChris Lattner 
210fdb533a1SChris Lattner   std::vector<std::pair<Function*, int> > M1Tors, M2Tors;
211fdb533a1SChris Lattner   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
212fdb533a1SChris Lattner   if (!InitList) return;
213fdb533a1SChris Lattner 
214fdb533a1SChris Lattner   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
215fdb533a1SChris Lattner     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
216fdb533a1SChris Lattner       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
217fdb533a1SChris Lattner 
218fdb533a1SChris Lattner       if (CS->getOperand(1)->isNullValue())
219fdb533a1SChris Lattner         break;  // Found a null terminator, stop here.
220fdb533a1SChris Lattner 
221e0fc4dfcSReid Spencer       ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
222e0fc4dfcSReid Spencer       int Priority = CI ? CI->getSExtValue() : 0;
223fdb533a1SChris Lattner 
224fdb533a1SChris Lattner       Constant *FP = CS->getOperand(1);
225fdb533a1SChris Lattner       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
2266c38f0bbSReid Spencer         if (CE->isCast())
227fdb533a1SChris Lattner           FP = CE->getOperand(0);
228fdb533a1SChris Lattner       if (Function *F = dyn_cast<Function>(FP)) {
2295301e7c6SReid Spencer         if (!F->isDeclaration())
230fdb533a1SChris Lattner           M1Tors.push_back(std::make_pair(F, Priority));
231fdb533a1SChris Lattner         else {
232fdb533a1SChris Lattner           // Map to M2's version of the function.
233956ae9dcSDan Gohman           F = cast<Function>(ValueMap[F]);
234fdb533a1SChris Lattner           M2Tors.push_back(std::make_pair(F, Priority));
235fdb533a1SChris Lattner         }
236fdb533a1SChris Lattner       }
237fdb533a1SChris Lattner     }
238fdb533a1SChris Lattner   }
239fdb533a1SChris Lattner 
240fdb533a1SChris Lattner   GV->eraseFromParent();
241fdb533a1SChris Lattner   if (!M1Tors.empty()) {
242fdb533a1SChris Lattner     Constant *M1Init = GetTorInit(M1Tors);
243b17f3294SOwen Anderson     new GlobalVariable(*M1, M1Init->getType(), false,
2445948fdf6SOwen Anderson                        GlobalValue::AppendingLinkage,
245b17f3294SOwen Anderson                        M1Init, GlobalName);
246fdb533a1SChris Lattner   }
247fdb533a1SChris Lattner 
248fdb533a1SChris Lattner   GV = M2->getNamedGlobal(GlobalName);
249fdb533a1SChris Lattner   assert(GV && "Not a clone of M1?");
250fdb533a1SChris Lattner   assert(GV->use_empty() && "llvm.ctors shouldn't have uses!");
251fdb533a1SChris Lattner 
252fdb533a1SChris Lattner   GV->eraseFromParent();
253fdb533a1SChris Lattner   if (!M2Tors.empty()) {
254fdb533a1SChris Lattner     Constant *M2Init = GetTorInit(M2Tors);
255b17f3294SOwen Anderson     new GlobalVariable(*M2, M2Init->getType(), false,
2565948fdf6SOwen Anderson                        GlobalValue::AppendingLinkage,
257b17f3294SOwen Anderson                        M2Init, GlobalName);
258fdb533a1SChris Lattner   }
259fdb533a1SChris Lattner }
260fdb533a1SChris Lattner 
261b417a5c1SPatrick Jenkins 
262567543f0SChris Lattner /// SplitFunctionsOutOfModule - Given a module and a list of functions in the
263567543f0SChris Lattner /// module, split the functions OUT of the specified module, and place them in
264567543f0SChris Lattner /// the new module.
265956ae9dcSDan Gohman Module *
266956ae9dcSDan Gohman llvm::SplitFunctionsOutOfModule(Module *M,
267956ae9dcSDan Gohman                                 const std::vector<Function*> &F,
268956ae9dcSDan Gohman                                 DenseMap<const Value*, Value*> &ValueMap) {
269567543f0SChris Lattner   // Make sure functions & globals are all external so that linkage
270567543f0SChris Lattner   // between the two modules will work.
271567543f0SChris Lattner   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
272567543f0SChris Lattner     I->setLinkage(GlobalValue::ExternalLinkage);
273fdb533a1SChris Lattner   for (Module::global_iterator I = M->global_begin(), E = M->global_end();
274c76bacbfSOwen Anderson        I != E; ++I) {
275d786b51eSDaniel Dunbar     if (I->hasName() && I->getName()[0] == '\01')
276d786b51eSDaniel Dunbar       I->setName(I->getName().substr(1));
277567543f0SChris Lattner     I->setLinkage(GlobalValue::ExternalLinkage);
278c76bacbfSOwen Anderson   }
279567543f0SChris Lattner 
280956ae9dcSDan Gohman   DenseMap<const Value*, Value*> NewValueMap;
281956ae9dcSDan Gohman   Module *New = CloneModule(M, NewValueMap);
282567543f0SChris Lattner 
2837275b02eSChris Lattner   // Make sure global initializers exist only in the safe module (CBE->.so)
2847275b02eSChris Lattner   for (Module::global_iterator I = New->global_begin(), E = New->global_end();
2857275b02eSChris Lattner        I != E; ++I)
2867275b02eSChris Lattner     I->setInitializer(0);  // Delete the initializer to make it external
287567543f0SChris Lattner 
2887275b02eSChris Lattner   // Remove the Test functions from the Safe module
289956ae9dcSDan Gohman   std::set<Function *> TestFunctions;
290567543f0SChris Lattner   for (unsigned i = 0, e = F.size(); i != e; ++i) {
291956ae9dcSDan Gohman     Function *TNOF = cast<Function>(ValueMap[F[i]]);
292d8db3760SDan Gohman     DEBUG(errs() << "Removing function ");
293d8db3760SDan Gohman     DEBUG(WriteAsOperand(errs(), TNOF, false));
294d8db3760SDan Gohman     DEBUG(errs() << "\n");
295956ae9dcSDan Gohman     TestFunctions.insert(cast<Function>(NewValueMap[TNOF]));
2967275b02eSChris Lattner     DeleteFunctionBody(TNOF);       // Function is now external in this module!
297567543f0SChris Lattner   }
298567543f0SChris Lattner 
299b417a5c1SPatrick Jenkins 
3007275b02eSChris Lattner   // Remove the Safe functions from the Test module
3017275b02eSChris Lattner   for (Module::iterator I = New->begin(), E = New->end(); I != E; ++I)
302956ae9dcSDan Gohman     if (!TestFunctions.count(I))
3037275b02eSChris Lattner       DeleteFunctionBody(I);
304b417a5c1SPatrick Jenkins 
305fdb533a1SChris Lattner 
306fdb533a1SChris Lattner   // Make sure that there is a global ctor/dtor array in both halves of the
307fdb533a1SChris Lattner   // module if they both have static ctor/dtor functions.
308956ae9dcSDan Gohman   SplitStaticCtorDtor("llvm.global_ctors", M, New, NewValueMap);
309956ae9dcSDan Gohman   SplitStaticCtorDtor("llvm.global_dtors", M, New, NewValueMap);
310fdb533a1SChris Lattner 
311567543f0SChris Lattner   return New;
312567543f0SChris Lattner }
313a060b10eSChris Lattner 
314a060b10eSChris Lattner //===----------------------------------------------------------------------===//
315a060b10eSChris Lattner // Basic Block Extraction Code
316a060b10eSChris Lattner //===----------------------------------------------------------------------===//
317a060b10eSChris Lattner 
318a060b10eSChris Lattner /// ExtractMappedBlocksFromModule - Extract all but the specified basic blocks
319a060b10eSChris Lattner /// into their own functions.  The only detail is that M is actually a module
320a060b10eSChris Lattner /// cloned from the one the BBs are in, so some mapping needs to be performed.
321a060b10eSChris Lattner /// If this operation fails for some reason (ie the implementation is buggy),
322a060b10eSChris Lattner /// this function should return null, otherwise it returns a new Module.
323a060b10eSChris Lattner Module *BugDriver::ExtractMappedBlocksFromModule(const
324a060b10eSChris Lattner                                                  std::vector<BasicBlock*> &BBs,
325a060b10eSChris Lattner                                                  Module *M) {
326c6243020SNick Lewycky   char *ExtraArg = NULL;
327c6243020SNick Lewycky 
328a53337f7SDaniel Dunbar   sys::Path uniqueFilename(OutputPrefix + "-extractblocks");
329c6243020SNick Lewycky   std::string ErrMsg;
330c6243020SNick Lewycky   if (uniqueFilename.createTemporaryFileOnDisk(true, &ErrMsg)) {
331ee05152cSDan Gohman     outs() << "*** Basic Block extraction failed!\n";
332d8db3760SDan Gohman     errs() << "Error creating temporary file: " << ErrMsg << "\n";
333c6243020SNick Lewycky     M = swapProgramIn(M);
334c6243020SNick Lewycky     EmitProgressBitcode("basicblockextractfail", true);
335c6243020SNick Lewycky     swapProgramIn(M);
336c6243020SNick Lewycky     return 0;
337c6243020SNick Lewycky   }
338c6243020SNick Lewycky   sys::RemoveFileOnSignal(uniqueFilename);
339c6243020SNick Lewycky 
340ee05152cSDan Gohman   std::string ErrorInfo;
34161a8796dSDan Gohman   raw_fd_ostream BlocksToNotExtractFile(uniqueFilename.c_str(), ErrorInfo);
342ee05152cSDan Gohman   if (!ErrorInfo.empty()) {
343ee05152cSDan Gohman     outs() << "*** Basic Block extraction failed!\n";
344ee05152cSDan Gohman     errs() << "Error writing list of blocks to not extract: " << ErrorInfo
345c6243020SNick Lewycky            << "\n";
346c6243020SNick Lewycky     M = swapProgramIn(M);
347c6243020SNick Lewycky     EmitProgressBitcode("basicblockextractfail", true);
348c6243020SNick Lewycky     swapProgramIn(M);
349c6243020SNick Lewycky     return 0;
350c6243020SNick Lewycky   }
351c6243020SNick Lewycky   for (std::vector<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
352c6243020SNick Lewycky        I != E; ++I) {
353c6243020SNick Lewycky     BasicBlock *BB = *I;
35497879424SChris Lattner     // If the BB doesn't have a name, give it one so we have something to key
35597879424SChris Lattner     // off of.
35697879424SChris Lattner     if (!BB->hasName()) BB->setName("tmpbb");
35712368685SDaniel Dunbar     BlocksToNotExtractFile << BB->getParent()->getNameStr() << " "
358c6243020SNick Lewycky                            << BB->getName() << "\n";
359c6243020SNick Lewycky   }
360c6243020SNick Lewycky   BlocksToNotExtractFile.close();
361c6243020SNick Lewycky 
362c6243020SNick Lewycky   const char *uniqueFN = uniqueFilename.c_str();
363c6243020SNick Lewycky   ExtraArg = (char*)malloc(23 + strlen(uniqueFN));
364c6243020SNick Lewycky   strcat(strcpy(ExtraArg, "--extract-blocks-file="), uniqueFN);
365c6243020SNick Lewycky 
366a060b10eSChris Lattner   std::vector<const PassInfo*> PI;
367c6243020SNick Lewycky   std::vector<BasicBlock *> EmptyBBs; // This parameter is ignored.
368c6243020SNick Lewycky   PI.push_back(getPI(createBlockExtractorPass(EmptyBBs)));
369c6243020SNick Lewycky   Module *Ret = runPassesOn(M, PI, false, 1, &ExtraArg);
370c6243020SNick Lewycky 
371c6243020SNick Lewycky   if (uniqueFilename.exists())
372c6243020SNick Lewycky     uniqueFilename.eraseFromDisk(); // Free disk space
373c6243020SNick Lewycky   free(ExtraArg);
374c6243020SNick Lewycky 
375af32dfa0SChris Lattner   if (Ret == 0) {
376ee05152cSDan Gohman     outs() << "*** Basic Block extraction failed, please report a bug!\n";
377af32dfa0SChris Lattner     M = swapProgramIn(M);
3780e535c3cSGabor Greif     EmitProgressBitcode("basicblockextractfail", true);
379917f8fd1SChris Lattner     swapProgramIn(M);
380af32dfa0SChris Lattner   }
381a060b10eSChris Lattner   return Ret;
382a060b10eSChris Lattner }
383