1 //===- ExtractFunction.cpp - Extract a function from Program --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #include "BugDriver.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/IR/Verifier.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"
37 #define DEBUG_TYPE "bugpoint"
40 bool DisableSimplifyCFG = false;
41 extern cl::opt<std::string> OutputPrefix;
42 } // End llvm namespace
47 cl::desc("Do not use the -dce pass to reduce testcases"));
49 NoSCFG("disable-simplifycfg", cl::location(DisableSimplifyCFG),
50 cl::desc("Do not use the -simplifycfg pass to reduce testcases"));
52 Function* globalInitUsesExternalBA(GlobalVariable* GV) {
53 if (!GV->hasInitializer())
56 Constant *I = GV->getInitializer();
58 // walk the values used by the initializer
59 // (and recurse into things like ConstantExpr)
60 std::vector<Constant*> Todo;
61 std::set<Constant*> Done;
64 while (!Todo.empty()) {
65 Constant* V = Todo.back();
69 if (BlockAddress *BA = dyn_cast<BlockAddress>(V)) {
70 Function *F = BA->getFunction();
71 if (F->isDeclaration())
75 for (User::op_iterator i = V->op_begin(), e = V->op_end(); i != e; ++i) {
76 Constant *C = dyn_cast<Constant>(*i);
77 if (C && !isa<GlobalValue>(C) && !Done.count(C))
83 } // end anonymous namespace
85 /// deleteInstructionFromProgram - This method clones the current Program and
86 /// deletes the specified instruction from the cloned module. It then runs a
87 /// series of cleanup passes (ADCE and SimplifyCFG) to eliminate any code which
88 /// depends on the value. The modified module is then returned.
90 Module *BugDriver::deleteInstructionFromProgram(const Instruction *I,
91 unsigned Simplification) {
93 Module *Clone = CloneModule(Program);
95 const BasicBlock *PBB = I->getParent();
96 const Function *PF = PBB->getParent();
98 Module::iterator RFI = Clone->begin(); // Get iterator to corresponding fn
99 std::advance(RFI, std::distance(PF->getParent()->begin(),
100 Module::const_iterator(PF)));
102 Function::iterator RBI = RFI->begin(); // Get iterator to corresponding BB
103 std::advance(RBI, std::distance(PF->begin(), Function::const_iterator(PBB)));
105 BasicBlock::iterator RI = RBI->begin(); // Get iterator to corresponding inst
106 std::advance(RI, std::distance(PBB->begin(), BasicBlock::const_iterator(I)));
107 Instruction *TheInst = RI; // Got the corresponding instruction!
109 // If this instruction produces a value, replace any users with null values
110 if (!TheInst->getType()->isVoidTy())
111 TheInst->replaceAllUsesWith(Constant::getNullValue(TheInst->getType()));
113 // Remove the instruction from the program.
114 TheInst->getParent()->getInstList().erase(TheInst);
116 // Spiff up the output a little bit.
117 std::vector<std::string> Passes;
119 /// Can we get rid of the -disable-* options?
120 if (Simplification > 1 && !NoDCE)
121 Passes.push_back("dce");
122 if (Simplification && !DisableSimplifyCFG)
123 Passes.push_back("simplifycfg"); // Delete dead control flow
125 Passes.push_back("verify");
126 Module *New = runPassesOn(Clone, Passes);
129 errs() << "Instruction removal failed. Sorry. :( Please report a bug!\n";
135 /// performFinalCleanups - This method clones the current Program and performs
136 /// a series of cleanups intended to get rid of extra cruft on the module
137 /// before handing it to the user.
139 Module *BugDriver::performFinalCleanups(Module *M, bool MayModifySemantics) {
140 // Make all functions external, so GlobalDCE doesn't delete them...
141 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
142 I->setLinkage(GlobalValue::ExternalLinkage);
144 std::vector<std::string> CleanupPasses;
145 CleanupPasses.push_back("globaldce");
147 if (MayModifySemantics)
148 CleanupPasses.push_back("deadarghaX0r");
150 CleanupPasses.push_back("deadargelim");
152 Module *New = runPassesOn(M, CleanupPasses);
154 errs() << "Final cleanups failed. Sorry. :( Please report a bug!\n";
162 /// ExtractLoop - Given a module, extract up to one loop from it into a new
163 /// function. This returns null if there are no extractable loops in the
164 /// program or if the loop extractor crashes.
165 Module *BugDriver::ExtractLoop(Module *M) {
166 std::vector<std::string> LoopExtractPasses;
167 LoopExtractPasses.push_back("loop-extract-single");
169 Module *NewM = runPassesOn(M, LoopExtractPasses);
171 outs() << "*** Loop extraction failed: ";
172 EmitProgressBitcode(M, "loopextraction", true);
173 outs() << "*** Sorry. :( Please report a bug!\n";
177 // Check to see if we created any new functions. If not, no loops were
178 // extracted and we should return null. Limit the number of loops we extract
179 // to avoid taking forever.
180 static unsigned NumExtracted = 32;
181 if (M->size() == NewM->size() || --NumExtracted == 0) {
185 assert(M->size() < NewM->size() && "Loop extract removed functions?");
186 Module::iterator MI = NewM->begin();
187 for (unsigned i = 0, e = M->size(); i != e; ++i)
195 // DeleteFunctionBody - "Remove" the function by deleting all of its basic
196 // blocks, making it external.
198 void llvm::DeleteFunctionBody(Function *F) {
199 // delete the body of the function...
201 assert(F->isDeclaration() && "This didn't make the function external!");
204 /// GetTorInit - Given a list of entries for static ctors/dtors, return them
205 /// as a constant array.
206 static Constant *GetTorInit(std::vector<std::pair<Function*, int> > &TorList) {
207 assert(!TorList.empty() && "Don't create empty tor list!");
208 std::vector<Constant*> ArrayElts;
209 Type *Int32Ty = Type::getInt32Ty(TorList[0].first->getContext());
212 StructType::get(Int32Ty, TorList[0].first->getType(), NULL);
213 for (unsigned i = 0, e = TorList.size(); i != e; ++i) {
215 ConstantInt::get(Int32Ty, TorList[i].second),
218 ArrayElts.push_back(ConstantStruct::get(STy, Elts));
220 return ConstantArray::get(ArrayType::get(ArrayElts[0]->getType(),
225 /// SplitStaticCtorDtor - A module was recently split into two parts, M1/M2, and
226 /// M1 has all of the global variables. If M2 contains any functions that are
227 /// static ctors/dtors, we need to add an llvm.global_[cd]tors global to M2, and
228 /// prune appropriate entries out of M1s list.
229 static void SplitStaticCtorDtor(const char *GlobalName, Module *M1, Module *M2,
230 ValueToValueMapTy &VMap) {
231 GlobalVariable *GV = M1->getNamedGlobal(GlobalName);
232 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage() ||
233 !GV->use_empty()) return;
235 std::vector<std::pair<Function*, int> > M1Tors, M2Tors;
236 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
237 if (!InitList) return;
239 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
240 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
241 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
243 if (CS->getOperand(1)->isNullValue())
244 break; // Found a null terminator, stop here.
246 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
247 int Priority = CI ? CI->getSExtValue() : 0;
249 Constant *FP = CS->getOperand(1);
250 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
252 FP = CE->getOperand(0);
253 if (Function *F = dyn_cast<Function>(FP)) {
254 if (!F->isDeclaration())
255 M1Tors.push_back(std::make_pair(F, Priority));
257 // Map to M2's version of the function.
258 F = cast<Function>(VMap[F]);
259 M2Tors.push_back(std::make_pair(F, Priority));
265 GV->eraseFromParent();
266 if (!M1Tors.empty()) {
267 Constant *M1Init = GetTorInit(M1Tors);
268 new GlobalVariable(*M1, M1Init->getType(), false,
269 GlobalValue::AppendingLinkage,
273 GV = M2->getNamedGlobal(GlobalName);
274 assert(GV && "Not a clone of M1?");
275 assert(GV->use_empty() && "llvm.ctors shouldn't have uses!");
277 GV->eraseFromParent();
278 if (!M2Tors.empty()) {
279 Constant *M2Init = GetTorInit(M2Tors);
280 new GlobalVariable(*M2, M2Init->getType(), false,
281 GlobalValue::AppendingLinkage,
287 /// SplitFunctionsOutOfModule - Given a module and a list of functions in the
288 /// module, split the functions OUT of the specified module, and place them in
291 llvm::SplitFunctionsOutOfModule(Module *M,
292 const std::vector<Function*> &F,
293 ValueToValueMapTy &VMap) {
294 // Make sure functions & globals are all external so that linkage
295 // between the two modules will work.
296 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
297 I->setLinkage(GlobalValue::ExternalLinkage);
298 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
300 if (I->hasName() && I->getName()[0] == '\01')
301 I->setName(I->getName().substr(1));
302 I->setLinkage(GlobalValue::ExternalLinkage);
305 ValueToValueMapTy NewVMap;
306 Module *New = CloneModule(M, NewVMap);
308 // Remove the Test functions from the Safe module
309 std::set<Function *> TestFunctions;
310 for (unsigned i = 0, e = F.size(); i != e; ++i) {
311 Function *TNOF = cast<Function>(VMap[F[i]]);
312 DEBUG(errs() << "Removing function ");
313 DEBUG(TNOF->printAsOperand(errs(), false));
314 DEBUG(errs() << "\n");
315 TestFunctions.insert(cast<Function>(NewVMap[TNOF]));
316 DeleteFunctionBody(TNOF); // Function is now external in this module!
320 // Remove the Safe functions from the Test module
321 for (Module::iterator I = New->begin(), E = New->end(); I != E; ++I)
322 if (!TestFunctions.count(I))
323 DeleteFunctionBody(I);
326 // Try to split the global initializers evenly
327 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
329 GlobalVariable *GV = cast<GlobalVariable>(NewVMap[I]);
330 if (Function *TestFn = globalInitUsesExternalBA(I)) {
331 if (Function *SafeFn = globalInitUsesExternalBA(GV)) {
332 errs() << "*** Error: when reducing functions, encountered "
334 GV->printAsOperand(errs(), false);
335 errs() << "' with an initializer that references blockaddresses "
336 "from safe function '" << SafeFn->getName()
337 << "' and from test function '" << TestFn->getName() << "'.\n";
340 I->setInitializer(nullptr); // Delete the initializer to make it external
342 // If we keep it in the safe module, then delete it in the test module
343 GV->setInitializer(nullptr);
347 // Make sure that there is a global ctor/dtor array in both halves of the
348 // module if they both have static ctor/dtor functions.
349 SplitStaticCtorDtor("llvm.global_ctors", M, New, NewVMap);
350 SplitStaticCtorDtor("llvm.global_dtors", M, New, NewVMap);
355 //===----------------------------------------------------------------------===//
356 // Basic Block Extraction Code
357 //===----------------------------------------------------------------------===//
359 /// ExtractMappedBlocksFromModule - Extract all but the specified basic blocks
360 /// into their own functions. The only detail is that M is actually a module
361 /// cloned from the one the BBs are in, so some mapping needs to be performed.
362 /// If this operation fails for some reason (ie the implementation is buggy),
363 /// this function should return null, otherwise it returns a new Module.
364 Module *BugDriver::ExtractMappedBlocksFromModule(const
365 std::vector<BasicBlock*> &BBs,
367 SmallString<128> Filename;
369 std::error_code EC = sys::fs::createUniqueFile(
370 OutputPrefix + "-extractblocks%%%%%%%", FD, Filename);
372 outs() << "*** Basic Block extraction failed!\n";
373 errs() << "Error creating temporary file: " << EC.message() << "\n";
374 EmitProgressBitcode(M, "basicblockextractfail", true);
377 sys::RemoveFileOnSignal(Filename);
379 tool_output_file BlocksToNotExtractFile(Filename.c_str(), FD);
380 for (std::vector<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
383 // If the BB doesn't have a name, give it one so we have something to key
385 if (!BB->hasName()) BB->setName("tmpbb");
386 BlocksToNotExtractFile.os() << BB->getParent()->getName() << " "
387 << BB->getName() << "\n";
389 BlocksToNotExtractFile.os().close();
390 if (BlocksToNotExtractFile.os().has_error()) {
391 errs() << "Error writing list of blocks to not extract\n";
392 EmitProgressBitcode(M, "basicblockextractfail", true);
393 BlocksToNotExtractFile.os().clear_error();
396 BlocksToNotExtractFile.keep();
398 std::string uniqueFN = "--extract-blocks-file=";
399 uniqueFN += Filename.str();
400 const char *ExtraArg = uniqueFN.c_str();
402 std::vector<std::string> PI;
403 PI.push_back("extract-blocks");
404 Module *Ret = runPassesOn(M, PI, false, 1, &ExtraArg);
406 sys::fs::remove(Filename.c_str());
409 outs() << "*** Basic Block extraction failed, please report a bug!\n";
410 EmitProgressBitcode(M, "basicblockextractfail", true);